﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PTTPOS_Solution.DAL;
using System.Drawing.Printing;
using System.Threading;
using System.Diagnostics;
using System.Printing;

namespace PTTPOS_Solution
{
    public partial class frmMain : Form
    {
        int h, w;
        string name = "";
        string id_order = "";
        Color color = new Color();
        int id_ban;
        string id_table = "";
        string id_place = "";
        string type_txtvalue = "";
        string valuePrint = "";
        string oldtable = "";
        string newtable = "";
        string place = "";
        string discount_value = "0";
        string discount_type = "0";
        string surcharge_value = "0";
        string surcharge_type = "0";
        string value_customer = "";
        string id_customer = "";
        string id_discount = "";
        string id_surcharge = "";
        decimal sumtotalsurcharge = 0;
        bool thaydoi = true;
        decimal phuthu_old = 0;
        decimal total_surcharge = 0;
        string nameTable = ""; // Biến để làm nút hủy bàn. Lấy tên bàn đang chọn
        bool fastbuy = false; // Biến để làm nút bán nhanh (true: cho phép bán nhanh / false: không cho phép)
        frmLogin flogin = new frmLogin();

        bool chk_login = false;

        public frmMain()
        {
            if (flogin.ShowDialog() == DialogResult.Yes)
            {
                chk_login = true;
            }
            else
            {
                chk_login = false;
            }
            //flogin.ShowDialog();
            InitializeComponent();
            //foreach (string item in PrinterSettings.InstalledPrinters)
            //{
            //    Print_DA.InsertPrinter(item); 
            //}
            h = Screen.PrimaryScreen.Bounds.Height;
            w = Screen.PrimaryScreen.Bounds.Width;
        }

        private void lblPay_MouseDown(object sender, MouseEventArgs e)
        {
            //lblPay.BackColor = Color.FromArgb(0, 0, 192);
        }

        private void lblPay_MouseUp(object sender, MouseEventArgs e)
        {
            //lblPay.BackColor = Color.DodgerBlue;
        }
        private void GetDate()
        {
            DateTime date;
            date = DateTime.Now;
            switch (date.DayOfWeek.ToString())
            {
                case "Monday": lblDate.Text = "Thứ 2, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Tuesday": lblDate.Text = "Thứ 3, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Wednesday": lblDate.Text = "Thứ 4, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Thursday": lblDate.Text = "Thứ 5, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Friday": lblDate.Text = "Thứ 6, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Saturday": lblDate.Text = "Thứ 7, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                case "Sunday": lblDate.Text = "Chủ nhật, " + date.Day + "/" + date.Month + "/" + date.Year; break;
                default: lblDate.Text = ""; break;
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.Hour.ToString() + " : " + DateTime.Now.Minute.ToString();
            GetDate();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                if (chk_login)
                {
                    if (Order_pro_DA.TotalOrder_pro())
                    {
                        Panel pn = new Panel();
                        pn.Size = this.Size;
                        pn.BackColor = Color.Black;
                        this.Controls.Add(pn);
                        pn.BringToFront();
                        MessageBox.Show("Hết hạn");
                        Application.Exit();
                    }
                    else
                    {

                        lblStaffName.Text = Account_DA.staffName;
                        lblCompanyName.Text = Account_DA.companyName;
                        //MyTactics.blogspot.com.NewResolution n =
                        //new MyTactics.blogspot.com.NewResolution(1024, 768);
                        lblTime.Text = DateTime.Now.Hour.ToString() + " : " + DateTime.Now.Minute.ToString();

                        GetDate();
                        CreateMenu();
                        GetTable();
                        lblQLNganh.Enabled = false;
                        lblQLNganh.Text = "...";
                        lblQLNganh.BackColor = Color.SaddleBrown;

                        lblQLNhom.Enabled = false;
                        lblQLNhom.Text = "...";
                        lblQLNhom.BackColor = Color.SaddleBrown;

                        lblQLBan.Enabled = false;
                        lblQLBan.Text = "...";
                        lblQLBan.BackColor = Color.DarkOliveGreen;
                        lstOrder.Items.Clear();
                        if (this.Controls.ContainsKey("keynum"))
                            this.Controls.Find("keynum", true)[0].Visible = false;

                        lblBan.Text = "";
                        lblTongGiam.Text = "0";
                        lblTongTien.Text = "0";
                        lblPhuThu.Text = "0";
                        txtValue.Text = "";
                        lblValTitle.Text = "Tìm món ăn";

                        foreach (Control ctrl in flowLayoutPanel1.Controls)
                        {
                            if (ctrl.Tag == null & ctrl.Name != "lblBreakTable" & ctrl.Name != "lblNoteMenu" & ctrl.Name != "lblFastBuy" & ctrl.Name != "lblCheckTable" & ctrl.Name != "lblReportShifts")
                            {
                                ctrl.Visible = true;
                            }
                            else
                                ctrl.Visible = false;
                        }

                        first_load();
                    }
                }
                else
                    Application.Exit();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void first_load() //chuyển text box dữ liệu ở trên thành tìm món ăn.
        {
            lblValTitle.Text = "Tìm món ăn";
            pictureBox1.Enabled = true;
            lstOrder.Focus();
            type_txtvalue = "findMenu";
        }
        private void CreateMenu()
        {
            //
            //
            //Clear
            //{
            List<Control> lstctrl = new List<Control>();
            foreach (Control ctrl in flowLayoutPanel2.Controls)
            {
                if (ctrl.Name != "lblQLNganh" && ctrl.Name != "lblQLNhom")
                    lstctrl.Add(ctrl);
            }
            for (int i = 0; i < lstctrl.Count; i++)
            {
                flowLayoutPanel2.Controls.Remove(lstctrl[i]);
            }
            lblQLNganh.Text = "...";
            lblQLNhom.Text = "...";
            //}

            Categories_DA.GetListCatagories();
            Groupitems_DA.GetListGroupitems();
            int status2 = Convert.ToInt32(Company_DA.getcompany().Rows[0][10].ToString());
            if (status2 == 0)
            {
                Menu_DA.GetListMenu(0);
            }
            else
                Menu_DA.GetListMenu(1);

            for (int i = 0; i < Categories_DA.ListCatagories.Rows.Count; i++)
            {
                Label lbl = new Label();
                lbl.Text = Categories_DA.ListCatagories.Rows[i][2].ToString();
                lbl.Name = "NG" + Categories_DA.ListCatagories.Rows[i][0].ToString();
                lbl.BackColor = Color.Chocolate;
                lbl.AutoSize = false;
                lbl.Visible = true;
                lbl.Font = new Font(new FontFamily("Microsoft Sans Serif"), 11);
                lbl.Size = new Size(87, 70);
                lbl.Margin = new Padding(3, 3, 0, 0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                flowLayoutPanel2.Controls.Add(lbl);
                lbl.Click += new EventHandler(lblNganh_Click);
            }
            for (int i = 0; i < Groupitems_DA.ListGroupitems.Rows.Count; i++)
            {
                Label lbl = new Label();
                lbl.Text = Groupitems_DA.ListGroupitems.Rows[i][2].ToString();
                lbl.Name = "NH" + Groupitems_DA.ListGroupitems.Rows[i][0].ToString();
                lbl.Tag = "NG" + Groupitems_DA.ListGroupitems.Rows[i][1].ToString();
                lbl.BackColor = Color.Chocolate;
                lbl.AutoSize = false;
                lbl.Visible = false;
                lbl.Font = new Font(new FontFamily("Microsoft Sans Serif"), 11);
                lbl.Size = new Size(87, 70);
                lbl.Margin = new Padding(3, 3, 0, 0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                flowLayoutPanel2.Controls.Add(lbl);
                lbl.Click += new EventHandler(lblNhom_Click);
            }

            for (int i = 0; i < Menu_DA.ListMenu.Rows.Count; i++)
            {
                Label lbl = new Label();
                lbl.Text = Menu_DA.ListMenu.Rows[i][2].ToString();
                lbl.Name = "TD" + Menu_DA.ListMenu.Rows[i][0].ToString();
                lbl.Tag = "NH" + Menu_DA.ListMenu.Rows[i][1].ToString();
                lbl.BackColor = Color.Chocolate;
                lbl.AutoSize = false;
                lbl.Visible = false;
                lbl.Font = new Font(new FontFamily("Microsoft Sans Serif"), 11);
                lbl.Size = new Size(87, 70);
                lbl.Margin = new Padding(3, 3, 0, 0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                flowLayoutPanel2.Controls.Add(lbl);
                lbl.Click += new EventHandler(lblTD_Click);
            }
        }

        private void GetTable()
        {
            //Clear
            //{
            List<Control> lstctrl = new List<Control>();
            foreach (Control ctrl in flowLayoutPanel3.Controls)
            {
                if (ctrl.Name != "lblQLBan")
                    lstctrl.Add(ctrl);
            }
            for (int i = 0; i < lstctrl.Count; i++)
            {
                flowLayoutPanel3.Controls.Remove(lstctrl[i]);
            }
            lblQLBan.Text = "...";
            //}

            Place_DA.GetListPlace();
            Table_DA.GetListTable();
            for (int i = 0; i < Place_DA.ListPlace.Rows.Count; i++)
            {
                Label lbl = new Label();
                lbl.Text = Place_DA.ListPlace.Rows[i][1].ToString();
                lbl.Name = "KV" + Place_DA.ListPlace.Rows[i][0].ToString();
                lbl.BackColor = Color.DarkGreen;
                lbl.AutoSize = false;
                lbl.Visible = true;
                lbl.Font = new Font(new FontFamily("Microsoft Sans Serif"), 11);
                lbl.Size = new Size(87, 70);
                lbl.Margin = new Padding(3, 3, 0, 0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                flowLayoutPanel3.Controls.Add(lbl);
                lbl.Click += new EventHandler(lblKhuVuc_Click);
            }
            for (int i = 0; i < Table_DA.ListTable.Rows.Count; i++)
            {
                Label lbl = new Label();
                lbl.Text = Table_DA.ListTable.Rows[i][2].ToString();
                lbl.Name = "B" + Table_DA.ListTable.Rows[i][0].ToString();
                lbl.Tag = "KV" + Table_DA.ListTable.Rows[i][1].ToString();
                lbl.AutoSize = false;
                lbl.Visible = false;
                lbl.Font = new Font(new FontFamily("Microsoft Sans Serif"), 11);
                lbl.Size = new Size(87, 70);
                lbl.Margin = new Padding(3, 3, 0, 0);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                if (Table_DA.ListTable.Rows[i][3].ToString() == "0")
                    lbl.BackColor = Color.DarkGreen;
                else if (Table_DA.ListTable.Rows[i][3].ToString() == "1")
                    lbl.BackColor = Color.DodgerBlue;
                flowLayoutPanel3.Controls.Add(lbl);
                lbl.Click += new EventHandler(lblBan_Click);
            }
        }

        private void lblNganh_Click(object sender, EventArgs e)
        {
            try
            {
                lblQLNganh.Text = ((Label)sender).Text;
                lblQLNganh.Enabled = true;
                lblQLNganh.BackColor = Color.SaddleBrown;
                foreach (Control ctr in flowLayoutPanel2.Controls)
                {
                    if (ctr.Name.Substring(0, 2) == "NH" && ctr.Tag.Equals(((Label)sender).Name))
                        ctr.Visible = true;
                    else if (ctr.Name.Substring(0, 2) == "NG")
                    {
                        ctr.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void lblNhom_Click(object sender, EventArgs e)
        {
            try
            {
                lblQLNhom.Text = ((Label)sender).Text;
                lblQLNhom.Enabled = true;
                lblQLNhom.BackColor = Color.SaddleBrown;
                lblQLNhom.Tag = ((Label)sender).Tag;
                foreach (Control ctr in flowLayoutPanel2.Controls)
                {
                    if (ctr.Name.Substring(0, 2) == "TD" && ctr.Tag.Equals(((Label)sender).Name))
                        ctr.Visible = true;
                    else if (ctr.Name.Substring(0, 2) == "NH")
                    {
                        ctr.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void lblKhuVuc_Click(object sender, EventArgs e)
        {
            try
            {
                id_place = ((Label)sender).Name;
                lblQLBan.Text = ((Label)sender).Text;
                lblQLBan.Enabled = true;
                lblQLBan.BackColor = Color.DarkOliveGreen;
                lblQLBan.Tag = ((Label)sender).Tag;
                foreach (Control ctr in flowLayoutPanel3.Controls)
                {
                    if (ctr.Name.Substring(0, 1) == "B" && ctr.Tag.Equals(((Label)sender).Name))
                    {
                        ctr.Visible = true;
                    }
                    else if (ctr.Name.Substring(0, 2) == "KV")
                    {
                        ctr.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void lblQLNganh_Click(object sender, EventArgs e)
        {
            try
            {
                lblQLNganh.Text = "...";
                lblQLNganh.BackColor = Color.SaddleBrown;
                lblQLNganh.Enabled = false;


                lblQLNhom.Text = "...";
                lblQLNhom.BackColor = Color.SaddleBrown;
                lblQLNhom.Enabled = false;

                foreach (Control ctr in flowLayoutPanel2.Controls)
                {
                    if (ctr.Name == "lblQLNganh" || ctr.Name == "lblQLNhom" || ctr.Name.Substring(0, 2) == "NG")
                        ctr.Visible = true;
                    else
                    {
                        ctr.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblQLNhom_Click(object sender, EventArgs e)
        {
            try
            {
                lblQLNhom.Text = "...";
                lblQLNhom.Enabled = false;
                lblQLNhom.BackColor = Color.SaddleBrown;
                foreach (Control ctr in flowLayoutPanel2.Controls)
                {
                    if (ctr.Tag == null)
                        ctr.Tag = "";
                    if (ctr.Name == "lblQLNganh" || ctr.Name == "lblQLNhom" || ctr.Tag.Equals(((Label)sender).Tag.ToString()))
                        ctr.Visible = true;
                    else
                    {
                        ctr.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblQLBan_Click(object sender, EventArgs e)
        {
            try
            {
                thaydoi = true;
                lblQLBan.Text = "...";
                lblQLBan.Enabled = false;
                lblQLBan.BackColor = Color.DarkOliveGreen;
                foreach (Control ctr in flowLayoutPanel3.Controls)
                {
                    if (ctr.Tag == null)
                        ctr.Tag = "";
                    if (ctr.Name == "lblQLBan" || ctr.Tag.Equals(((Label)sender).Tag.ToString()))
                        ctr.Visible = true;
                    else
                    {
                        ctr.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        string act = "";
        private void lblBan_Click(object sender, EventArgs e)
        {
            try
            {
                nameTable = ((Label)sender).Name;

                thaydoi = true;
                phuthu_old = 0;

                if (act == "") // Xét nếu không có hành động gì (tức là bình thường)
                {
                    if (fastbuy) // Xét nếu kích hoạt chức năng bán nhanh thì không cho chọn bàn
                    {
                        MessageBox.Show("Đang kích hoạt chức năng bán nhanh, không chọn bàn được", "Thông báo");
                    }
                    else
                    {
                        if (lstOrder.Groups[1].Items.Count > 0)
                        {
                            if (((Label)sender).Name != "B" + id_ban.ToString())
                            {
                                DialogResult dialog = MessageBox.Show("Hóa đơn chưa được in xuống bếp? Bạn có muốn in không?", "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                                if (dialog == DialogResult.Yes)
                                {
                                    lblIn_Click(sender, e);
                                }
                                else if (dialog == DialogResult.Cancel)
                                    return;
                            }
                            else
                            {
                                return;
                            }
                        }
                        if (name != "")
                            flowLayoutPanel3.Controls.Find(name, true)[0].BackColor = color;
                        name = ((Label)sender).Name;
                        color = ((Label)sender).BackColor;

                        if (((Label)sender).BackColor == Color.DarkGreen)
                            ((Label)sender).BackColor = Color.DarkSeaGreen;
                        else
                            ((Label)sender).BackColor = Color.SkyBlue;

                        if (color == Color.DodgerBlue) // Xét nếu bàn có màu DogerBlue (Tức là màu bàn đã có order)
                        {
                            ClickOnTable(((Label)sender).Name.Substring(1));//Phương thức này dùng chung cho tách bàn
                        }
                        else
                        {
                            id_order = "";
                            id_customer = "";
                            value_customer = "";
                            id_discount = "";
                            id_surcharge = "";
                            surcharge_type = "0";
                            surcharge_value = "0";
                            discount_type = "0";
                            discount_value = "0";
                            total_surcharge = 0;
                            sumtotalsurcharge = 0;
                            lstOrder.Items.Clear();

                            lblPhuThu.Text = "0";
                            lblTongGiam.Text = "0";
                            lblTongTien.Text = "0";
                        }
                        lblBan.Text = ((Label)sender).Text;
                        id_ban = Convert.ToInt16(((Label)sender).Name.Substring(1, ((Label)sender).Name.Length - 1));
                        //id_place = ((Label)sender).Name;
                        id_table = ((Label)sender).Name; // Lấy tên của bàn đang chọn.
                    }
                }
                else if (act == "Swaptable")
                {
                    //id_table = ((Label)sender).Name; // Lấy tên của bàn đang chọn.
                    if (((Label)sender).BackColor == Color.DodgerBlue)
                        ((Label)sender).BackColor = Color.SkyBlue;
                    if (((Label)sender).BackColor == Color.DarkGreen)
                    {
                        ((Label)sender).BackColor = Color.DarkSeaGreen;
                        if ((MessageBox.Show("Bạn muốn chuyển từ " + oldtable + "-" + place + " Sang " + ((Label)sender).Text + "-" + flowLayoutPanel3.Controls[id_place].Text + " không?", "Ask", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
                        {
                            newtable = ((Label)sender).Name.Substring(1);
                            Order_pro_DA.Swaptable_pro(newtable, id_order);
                            Table_DA.updatetableWithstatus(id_ban.ToString(), "0");
                            Table_DA.updatetableWithstatus(newtable, "1");
                            ((Label)sender).BackColor = Color.SkyBlue;
                            lblBan.Text = ((Label)sender).Text;
                            flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor = Color.DarkGreen;
                            MessageBox.Show("Đã chuyển", "Success");
                            name = ((Label)sender).Name;
                            canSwap(true);
                            id_table = name;
                        }
                        else
                        {
                            ((Label)sender).BackColor = Color.DarkGreen;
                        }
                    }
                    else if (((Label)sender).BackColor == Color.SkyBlue)
                    {
                        MessageBox.Show("Bản phải chọn bàn chưa có order", "Err");
                        if (((Label)sender).BackColor == Color.SkyBlue)
                            ((Label)sender).BackColor = Color.DodgerBlue;
                    }
                }
                else if (act == "Compile")
                {
                    if (((Label)sender).BackColor == Color.DodgerBlue)
                    {
                        ((Label)sender).BackColor = Color.SkyBlue;
                        if ((MessageBox.Show("Bạn muốn gộp bàn từ " + oldtable + "-" + place + " Sang " + ((Label)sender).Text + "-" + flowLayoutPanel3.Controls[id_place].Text + " không?", "Ask", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
                        {
                            string old_discount = id_discount, old_customer = id_customer, old_order = id_order;
                            string old_surcharge = id_surcharge, old_valueSurcharge = surcharge_value, old_typeSurcharge = surcharge_type;
                            decimal old_totalsurcharge = total_surcharge;
                            Order_pro_DA.FindOrder_pro(((Label)sender).Name.Substring(1));
                            if (Order_pro_DA.ListFindOrder.Rows.Count > 0)
                            {
                                id_discount = Order_pro_DA.ListFindOrder.Rows[0][5].ToString();
                                id_surcharge = Order_pro_DA.ListFindOrder.Rows[0][4].ToString();
                                total_surcharge = Convert.ToDecimal(Order_pro_DA.ListFindOrder.Rows[0][7].ToString());
                                if (id_surcharge != "")
                                {
                                    DataTable tbl = new DataTable();
                                    tbl = Surcharge_DAL.listSurcharge(id_surcharge);
                                    surcharge_type = tbl.Rows[0]["Rebateform"].ToString();
                                    surcharge_value = tbl.Rows[0]["Value"].ToString();
                                }
                                else
                                {
                                    surcharge_value = "0";
                                }
                                id_order = Order_pro_DA.ListFindOrder.Rows[0][0].ToString();
                                lstOrder.Items.Clear();
                                Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
                                if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                                    Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
                                if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                                {
                                    foreach (DataRow r in Orderdetails_pro_DA.ListOrderdetails.Rows)
                                    {
                                        ListViewItem a = new ListViewItem();

                                        ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                        b.Text = r["Amount"].ToString();
                                        ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                        f.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                                        if (r["Price2"].ToString() == r["Price"].ToString())
                                        {
                                            a.Text = r["Name"].ToString();
                                            c.Text = r["Price2"].ToString();
                                        }
                                        else
                                        {
                                            c.Text = (Convert.ToDecimal(r["Price2"])).ToString("N0");
                                            a.Text = "#" + r["Name"].ToString();
                                        }
                                        ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                        d.Text = r["ID"].ToString();
                                        ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                        g.Text = "0";
                                        a.SubItems.Add(b);
                                        a.SubItems.Add(c);
                                        a.SubItems.Add(d);
                                        a.SubItems.Add(g);
                                        a.SubItems.Add(f);
                                        a.Group = lstOrder.Groups[0];
                                        lstOrder.Items.Add(a);
                                        sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));
                                    }
                                }
                                Orderdetail2s_pro_DA.GetListOrderdetail2s_pro(id_order);
                                if (Orderdetail2s_pro_DA.ListOrderdetail2s.Rows.Count > 0)
                                {
                                    foreach (DataRow r in Orderdetail2s_pro_DA.ListOrderdetail2s.Rows)
                                    {
                                        ListViewItem a = new ListViewItem();
                                        a.Text = r["Productname"].ToString();
                                        ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                        b.Text = r["Amount"].ToString();
                                        ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                        c.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                                        ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                        d.Text = r["ID"].ToString();
                                        ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                        g.Text = "1";
                                        ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                        f.Text = r["Price"].ToString();
                                        a.SubItems.Add(b);
                                        a.SubItems.Add(c);
                                        a.SubItems.Add(d);
                                        a.SubItems.Add(g);
                                        a.SubItems.Add(f);
                                        a.Group = lstOrder.Groups[0];
                                        lstOrder.Items.Add(a);
                                        sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));

                                    }
                                }
                                total_surcharge = total_surcharge - sumtotalsurcharge * Convert.ToDecimal(surcharge_value) * (decimal)0.01;
                                sumtotalsurcharge = 0;

                            }
                            if ((old_customer != "" || old_discount != "") && (id_discount != "" || id_customer != ""))
                            {
                                DialogResult dialog = MessageBox.Show("Chọn gói giảm giá \n (Yes - Bàn nguồn | No - Bàn đích | Cancel - Hủy)", "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
                                if (dialog == DialogResult.Yes)
                                {
                                    Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                    Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                    Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                    Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                    Table_DA.updatetableWithstatus(id_ban.ToString(), "0");
                                    Order_pro_DA.DeleteOrder_pro(old_order);
                                    Order_pro_DA.UpdateOrders_pro_Compile(id_order, old_discount == "" ? null : old_discount, old_customer == "" ? null : old_customer);
                                    Discounts_DA.DeleteDiscount(id_discount);
                                }
                                else if (dialog == DialogResult.No)
                                {
                                    Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                    Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                    Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                    Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                    Table_DA.updatetableWithstatus(id_ban.ToString(), "0");
                                    Order_pro_DA.DeleteOrder_pro(old_order);
                                    Order_pro_DA.UpdateOrders_pro_Compile(id_order, id_discount == "" ? null : id_discount, id_customer == "" ? null : id_customer);
                                    Discounts_DA.DeleteDiscount(old_discount);
                                }
                                else
                                {
                                    ((Label)sender).BackColor = Color.DodgerBlue;
                                    return;
                                }
                            }
                            else if ((old_customer != "" || old_discount != ""))
                            {
                                Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                Table_DA.updatetableWithstatus(id_ban.ToString(), "0");
                                Order_pro_DA.DeleteOrder_pro(old_order);
                                Order_pro_DA.UpdateOrders_pro_Compile(id_order, old_discount == "" ? null : old_discount, old_customer == "" ? null : old_customer);
                                Discounts_DA.DeleteDiscount(id_discount);
                            }
                            else
                            {
                                Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                Orderdetails_pro_DA.CompileTableorderdetail_pro(id_order, old_order);
                                Orderdetail2s_pro_DA.CompileTableorderdetail2_pro(id_order, old_order);
                                Table_DA.updatetableWithstatus(id_ban.ToString(), "0");
                                Order_pro_DA.DeleteOrder_pro(old_order);
                                Order_pro_DA.UpdateOrders_pro_Compile(id_order, id_discount == "" ? null : id_discount, id_customer == "" ? null : id_customer);
                                Discounts_DA.DeleteDiscount(old_discount);
                            }

                            //Phụ thu

                            if (id_surcharge != "" && old_surcharge != "")
                            {
                                if (Convert.ToInt16(old_valueSurcharge) > Convert.ToInt16(surcharge_value))
                                {
                                    id_surcharge = old_surcharge;
                                    surcharge_value = old_valueSurcharge;
                                    surcharge_type = "1";
                                }
                                //Order_DA_pro.UpdateOrdersSurcharge_Compile(id_order, id_surcharge == "" ? null : id_surcharge);
                            }
                            else if (id_surcharge != "" || old_surcharge != "")
                            {
                                if (Convert.ToInt16(old_valueSurcharge) > Convert.ToInt16(surcharge_value))
                                {
                                    id_surcharge = old_surcharge;
                                    surcharge_value = old_valueSurcharge;
                                    surcharge_type = "1";

                                }

                                //Order_DA_pro.UpdateOrdersSurcharge_Compile(id_order, id_surcharge == "" ? null : id_surcharge);
                            }

                            total_surcharge += old_totalsurcharge;

                            lstOrder.Items.Clear();
                            Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
                            if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                                Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
                            if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                            {
                                foreach (DataRow r in Orderdetails_pro_DA.ListOrderdetails.Rows)
                                {
                                    ListViewItem a = new ListViewItem();

                                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                    b.Text = r["Amount"].ToString();
                                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                    ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                    f.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                                    if (r["Price2"].ToString() == r["Price"].ToString())
                                    {
                                        a.Text = r["Name"].ToString();
                                        c.Text = r["Price2"].ToString();
                                    }
                                    else
                                    {
                                        c.Text = (Convert.ToDecimal(r["Price2"])).ToString("N0");
                                        a.Text = "#" + r["Name"].ToString();
                                    }
                                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                    d.Text = r["ID"].ToString();
                                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                    g.Text = "0";
                                    a.SubItems.Add(b);
                                    a.SubItems.Add(c);
                                    a.SubItems.Add(d);
                                    a.SubItems.Add(g);
                                    a.SubItems.Add(f);
                                    a.Group = lstOrder.Groups[0];
                                    lstOrder.Items.Add(a);
                                    sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));
                                }
                            }
                            Orderdetail2s_pro_DA.GetListOrderdetail2s_pro(id_order);
                            if (Orderdetail2s_pro_DA.ListOrderdetail2s.Rows.Count > 0)
                            {
                                foreach (DataRow r in Orderdetail2s_pro_DA.ListOrderdetail2s.Rows)
                                {
                                    ListViewItem a = new ListViewItem();
                                    a.Text = r["Productname"].ToString();
                                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                    b.Text = r["Amount"].ToString();
                                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                    c.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                    d.Text = r["ID"].ToString();
                                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                    g.Text = "1";
                                    ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                    f.Text = r["Price"].ToString();
                                    a.SubItems.Add(b);
                                    a.SubItems.Add(c);
                                    a.SubItems.Add(d);
                                    a.SubItems.Add(g);
                                    a.SubItems.Add(f);
                                    a.Group = lstOrder.Groups[0];
                                    lstOrder.Items.Add(a);
                                    sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));

                                }
                            }
                            sumtotalsurcharge = sumtotalsurcharge * Convert.ToDecimal(surcharge_value) * (decimal)0.01;
                            lblPhuThu.Text = (sumtotalsurcharge + total_surcharge).ToString();
                            Order_pro_DA.UpdateOrdersSurcharge_pro_Compile(id_order, id_surcharge == "" ? null : id_surcharge, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                            tinhtong();
                            Order_pro_DA.UpdateOrdersSurcharge_pro_Compile(id_order, id_surcharge == "" ? null : id_surcharge, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                            flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor = Color.DarkGreen;
                            ((Label)sender).BackColor = Color.SkyBlue;
                            sumtotalsurcharge = 0; total_surcharge = 0;
                            name = ((Label)sender).Name;

                            Order_pro_DA.FindOrder_pro(((Label)sender).Name.Substring(1));
                            if (Order_pro_DA.ListFindOrder.Rows.Count > 0)
                            {
                                id_discount = Order_pro_DA.ListFindOrder.Rows[0][5].ToString();
                                if (id_discount != "")
                                {
                                    DataTable tbl = new DataTable();
                                    tbl = Discounts_DA.listDiscount(id_discount);
                                    discount_type = tbl.Rows[0]["Rebateform"].ToString();
                                    discount_value = tbl.Rows[0]["Value"].ToString();
                                }
                                else
                                {
                                    discount_type = "0";
                                    discount_value = "0";
                                }
                            }
                            decimal total = 0;
                            foreach (ListViewItem item in lstOrder.Groups[0].Items)
                            {
                                total += Convert.ToDecimal(item.SubItems[1].Text) * Convert.ToDecimal(item.SubItems[2].Text);
                            }
                            decimal discount = 0;
                            if (discount_type == "1")
                            {
                                discount = (Convert.ToDecimal(discount_value) * total * (decimal)0.01);
                            }
                            else if (discount_type == "2")
                            {
                                discount = Convert.ToDecimal(discount_value);
                            }

                            lblTongGiam.Text = discount.ToString();
                            tinhtong();
                            Order_pro_DA.UpdateOrdersDiscount_pro_Compile(id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            cancelCompile(true);
                            MessageBox.Show("Đã gộp", "Thông báo");
                            lblBan.Text = ((Label)sender).Text;
                            id_table = name;
                        }
                        else
                            ((Label)sender).BackColor = Color.DodgerBlue;
                    }
                    else if (((Label)sender).BackColor == Color.DarkGreen)
                    {
                        ((Label)sender).BackColor = Color.DarkSeaGreen;
                        MessageBox.Show("Phải chọn bàn có order", "Err");
                        ((Label)sender).BackColor = Color.DarkGreen;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ClickOnTable(string idBan)
        {
            Order_pro_DA.FindOrder_pro(idBan);
            if (Order_pro_DA.ListFindOrder.Rows.Count > 0)
            {
                id_discount = Order_pro_DA.ListFindOrder.Rows[0][5].ToString();
                id_surcharge = Order_pro_DA.ListFindOrder.Rows[0][4].ToString();
                id_order = Order_pro_DA.ListFindOrder.Rows[0][0].ToString();
                total_surcharge = Convert.ToDecimal(Order_pro_DA.ListFindOrder.Rows[0][7].ToString());
                if (id_discount != "")
                {
                    DataTable tbl = new DataTable();
                    tbl = Discounts_DA.listDiscount(id_discount);
                    discount_type = tbl.Rows[0]["Rebateform"].ToString();
                    discount_value = tbl.Rows[0]["Value"].ToString();
                }
                else
                {
                    discount_type = "0";
                    discount_value = "0";
                }
                if (id_surcharge != "")
                {
                    DataTable tbl = new DataTable();
                    tbl = Surcharge_DAL.listSurcharge(id_surcharge);
                    surcharge_type = tbl.Rows[0]["Rebateform"].ToString();
                    surcharge_value = tbl.Rows[0]["Value"].ToString();
                }
                else
                {
                    surcharge_type = "0";
                    surcharge_value = "0";
                }
            }
            else
            {
                id_discount = "";
                id_surcharge = "";
                id_order = "";
                id_customer = "";
            }

            lstOrder.Items.Clear();
            Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
            if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
            if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
            {
                foreach (DataRow r in Orderdetails_pro_DA.ListOrderdetails.Rows)
                {
                    ListViewItem a = new ListViewItem();

                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                    b.Text = r["Amount"].ToString();
                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                    ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                    f.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                    if (r["Price2"].ToString() == r["Price"].ToString())
                    {
                        a.Text = r["Name"].ToString();
                        c.Text = (Convert.ToDecimal(r["Price2"])).ToString("N0");
                    }
                    else
                    {
                        c.Text = (Convert.ToDecimal(r["Price2"])).ToString("N0");
                        a.Text = "#" + r["Name"].ToString();
                    }
                    //MessageBox.Show(r["Price2"].ToString());
                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                    d.Text = r["ID"].ToString();
                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                    g.Text = "0";
                    a.SubItems.Add(b);
                    a.SubItems.Add(c);
                    a.SubItems.Add(d);
                    a.SubItems.Add(g);
                    a.SubItems.Add(f);
                    a.Group = lstOrder.Groups[0];
                    lstOrder.Items.Add(a);
                    sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));
                }
            }
            Orderdetail2s_pro_DA.GetListOrderdetail2s_pro(id_order);
            if (Orderdetail2s_pro_DA.ListOrderdetail2s.Rows.Count > 0)
            {
                foreach (DataRow r in Orderdetail2s_pro_DA.ListOrderdetail2s.Rows)
                {
                    ListViewItem a = new ListViewItem();
                    a.Text = r["Productname"].ToString();
                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                    b.Text = r["Amount"].ToString();
                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                    c.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                    d.Text = r["ID"].ToString();
                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                    g.Text = "1";
                    ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                    f.Text = (Convert.ToDecimal(r["Price"])).ToString("N0");
                    a.SubItems.Add(b);
                    a.SubItems.Add(c);
                    a.SubItems.Add(d);
                    a.SubItems.Add(g);
                    a.SubItems.Add(f);
                    a.Group = lstOrder.Groups[0];
                    lstOrder.Items.Add(a);
                    sumtotalsurcharge = sumtotalsurcharge + (Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text));
                }
            }
            total_surcharge = total_surcharge - sumtotalsurcharge * Convert.ToDecimal(surcharge_value) * (decimal)0.01;
            sumtotalsurcharge = 0;
            lblPhuThu.Text = Convert.ToDecimal(Order_pro_DA.ListFindOrder.Rows[0][7]).ToString("N0");
            lblTongGiam.Text = Convert.ToDecimal(Order_pro_DA.ListFindOrder.Rows[0][8]).ToString("N0");
            lblTongTien.Text = Convert.ToDecimal(Order_pro_DA.ListFindOrder.Rows[0][9]).ToString("N0");
        }

        private bool KiemTraDinhLuong(int id, int value)
        {
            Formulas_DA.GetListFormulas(id);
            foreach (DataRow r in Formulas_DA.ListFormulas.Rows)
            {
                Materials_DA.GetListMaterial(r[0].ToString());
                decimal ketqua = 0;
                if (r[2].ToString() == Materials_DA.ListMaterial.Rows[0][2].ToString())
                {
                    ketqua = Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) - (Convert.ToDecimal(r[1]) * value);
                    if (ketqua < 0)
                    {
                        MessageBox.Show("Món này đã hết");
                        return false;
                    }
                }
                else
                {
                    Units_DA.GetListUnit(Materials_DA.ListMaterial.Rows[0][2].ToString());
                    do
                    {
                        if (Units_DA.ListUnit.Rows.Count > 0)
                        {
                            if (Units_DA.ListUnit.Rows[0][2].ToString() == r[2].ToString())
                            {
                                ketqua = Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) - ((Convert.ToDecimal(r[1]) / Convert.ToDecimal(Units_DA.ListUnit.Rows[0][3])) * value);
                                if (ketqua < 0)
                                {
                                    MessageBox.Show("Món này đã hết");
                                    return false;
                                }
                                else
                                    break;
                            }
                            else
                            {
                                Units_DA.GetListUnit(Units_DA.ListUnit.Rows[0][2].ToString());
                            }
                        }
                        else
                        {
                            MessageBox.Show("Không thể chuyển đổi định lượng trong công thức số: " + r[3].ToString(), "Lỗi định lượng", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                            return false;
                        }
                    } while (true);
                }
            }
            return true;
        }
        bool chk_discount = false; // Biến kiểm tra món ăn có chương trình khuyến mãi hay không
        private void lblTD_Click(object sender, EventArgs e)
        {
            try
            {
                if (lblBan.Text != "" || fastbuy)
                {
                    foreach (DataRow r in Menu_DA.ListMenu.Rows)
                    {
                        if (((Label)sender).Name.Substring(2, ((Label)sender).Name.Length - 2) == r[0].ToString())
                        {
                            //if (r[7].ToString() == "1")
                            //{
                            bool them = true;
                            if (lstOrder.Groups[1].Items.Count > 0)
                            {
                                foreach (ListViewItem a in lstOrder.Groups[1].Items)
                                {
                                    if (a.SubItems[3].Text == r["ID"].ToString())
                                    {
                                        if (KiemTraDinhLuong(Convert.ToInt32(r[0]), Convert.ToInt32(a.SubItems[1].Text) + 1) == true)
                                        {
                                            them = false;
                                            a.SubItems[1].Text = (Convert.ToDecimal(a.SubItems[1].Text) + 1).ToString();
                                            break;
                                        }
                                        else
                                            return;
                                    }
                                }
                            }
                            if (them == true)
                            {
                                if (KiemTraDinhLuong(Convert.ToInt32(r[0]), 1) == true)
                                {
                                    ListViewItem a = new ListViewItem();

                                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                    b.Text = "1";
                                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                    ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                    f.Text = Convert.ToDecimal(r["Price"]).ToString("N0");
                                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                    g.Text = Convert.ToDecimal(r["Price"]).ToString("N0");
                                    ListViewItem.ListViewSubItem h = new ListViewItem.ListViewSubItem();
                                    h.Text = "";
                                    h.Name = "NoteMenu";
                                    if (r["Rebateform"].ToString() == "0")
                                    {
                                        c.Text = Convert.ToDecimal(r["Price"]).ToString("N0");
                                        a.Text = r["Name"].ToString();
                                        chk_discount = false;
                                    }
                                    else if (r["Rebateform"].ToString() == "1")
                                    {
                                        chk_discount = true;
                                        c.Text = (Convert.ToDecimal(r["Price"]) - Convert.ToDecimal(r["Price"]) * Convert.ToDecimal(r["Value"]) * (decimal)(0.01)).ToString("N0");
                                        a.Text = "#" + r["Name"].ToString();
                                    }
                                    else if (r["Rebateform"].ToString() == "2")
                                    {
                                        chk_discount = true;
                                        c.Text = (Convert.ToDecimal(r["Price"]) - Convert.ToDecimal(r["Value"])).ToString("N0");
                                        a.Text = "#" + r["Name"].ToString();
                                    }
                                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                    d.Text = r["ID"].ToString();

                                    a.SubItems.Add(b);
                                    a.SubItems.Add(c);
                                    a.SubItems.Add(d);
                                    a.SubItems.Add(f);
                                    a.SubItems.Add(g);
                                    a.SubItems.Add(h);
                                    a.Group = lstOrder.Groups[1];
                                    lstOrder.Items.Add(a);
                                }
                                else
                                    return;
                            }
                            tinhtong();
                            break;
                        }
                    }
                }
                else
                    MessageBox.Show("Chưa chọn bàn", "Thông báo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            MyTactics.blogspot.com.NewResolution n = new MyTactics.blogspot.com.NewResolution(w, h);
        }

        private void lblPay_Click(object sender, EventArgs e) // Sự kiện click nút tính tiền
        {
            typePay = "pay"; 
            bool chk = false;  // Biến kiểm tra món chưa in ( true: món chưa in )
            try
            {
                /*
                 * Xét chưa order món ăn (lstOrder.Items.Count == 0) và phải xét thêm id_order
                 * Bởi vì trường hợp hủy hết món ăn nhưng id_order vẫn còn thì bàn đó vẫn cho là có order.
                */
                if (lstOrder.Items.Count == 0 && id_order == "") 
                    MessageBox.Show("Chưa order món ăn"); // Nếu chưa có món order thì thông báo lỗi.
                else
                {
                    /*
                     * Chỗ này phải cần có 1 biến chk, bởi vì tránh trường hợp hiện message box hỏi nhiều lần.
                    */
                    if (lstOrder.Groups[1].Items.Count > 0) // Xét có món đang gọi chưa in xuống bếp
                    {
                        DialogResult dialog = MessageBox.Show("Có món đang gọi chưa in xuống bếp, bạn muốn tính tiền bàn này không?", "Pay", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                        if (dialog == DialogResult.Yes) // Nếu đồng ý
                            chk = true;
                        else
                            return;
                    }
                    if (chk || MessageBox.Show("Bạn muốn tính tiền bàn này không?", "Pay", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        if (chk)
                        {
                            lblIn_Click(sender, e); // Lệnh in món xuống bếp
                        }

                        bool chk_print = false; //Biến kiểm tra tồn tại của máy in ( true: tồn tại / false: không tồn tại )
                        bool chk_queue = false; //Biến kiểm tra dữ liệu in trong queue ( true: trống / false: có dữ liệu )

                        PrintDocument prtDocument = new PrintDocument(); // Khởi tạo 1 đối tượng dùng để thao tác in ấn.
                        if (lstOrder.Items.Count > 0)
                        {
                            // Tạo 1 sự kiện PrintPage, để định nghĩa nội dung trang in
                            prtDocument.PrintPage += prtDocument_PrintPage; 

                            //Lấy tên máy in trong bảng company làm máy in bill
                            prtDocument.PrinterSettings.PrinterName = 
                                Print_DA.findNameprinterbyID(Company_DA.getcompany().Rows[0]["printbill"].ToString());
                            
                            // Duyệt tên các máy in được cài đặt trong máy để kiểm tra sự tồn tại của máy in.
                            foreach (string item in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                            {
                                if (item == prtDocument.PrinterSettings.PrinterName)
                                {
                                    chk_print = true;

                                    //Kiểm tra dữ liệu in có nằm trong queue chưa được in không
                                    PrintQueue queues = null;
                                    PrintServer printserver = new PrintServer();
                                    queues = printserver.GetPrintQueue(prtDocument.PrinterSettings.PrinterName);
                                    if (queues.NumberOfJobs > 0)
                                    {
                                        MessageBox.Show("Lỗi máy in " + prtDocument.PrinterSettings.PrinterName + ", in không thành công", "Err");
                                        chk_queue = false;
                                    }
                                    else
                                    {
                                        chk_queue = true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            chk_print = true; chk_queue = true;
                        }
                        if (chk_print && chk_queue) // Kiểm tra tồn tại máy in Và dữ liệu in trong queue
                        {
                            // Ở đây phải xét thêm 1 lần nữa vì trường hợp bàn có order nhưng đã hủy hết món nên sẽ không thực hiện in hóa đơn
                            if (lstOrder.Items.Count > 0) 
                                prtDocument.Print();

                            // Lưu dữ liệu từ bảng order tạm qua bảng order chính
                            Order_DA.AppendOrder(id_order);
                            Orderdetails_DA.AppendOrderdetails(id_order);
                            Orderdetail2s_DA.AppendOrderdetail2s(id_order);

                            // Xóa dữ liệu trong order bảng tạm
                            Orderdetail2s_pro_DA.delete_pro1(id_order);
                            Orderdetails_pro_DA.delete_pro1(id_order);
                            Order_pro_DA.DeleteOrder_pro(id_order);

                            // Cập nhật lại trạng thái bàn.
                            if (!fastbuy)
                            {
                                Table_DA.updatetableWithstatus(id_ban.ToString(), "0");

                                // Lưu vào nhật ký
                                //string s = "Nhân viên " + Account_DA.staffName + " đã thanh toán hóa đơn trị giá " + lblTongTien.Text + " VNĐ.";
                                //Diary_DA.Insert(Account_DA.staff_ID, s, DateTime.Now);

                                flowLayoutPanel3.Controls[id_table].BackColor = Color.DarkGreen; // Đổi màu bàn thành xanh lá (bàn trống)
                                color = Color.DarkGreen;
                            }
                            //Reset dữ liệu tĩnh trên form
                            lstOrder.Items.Clear();
                            lblTongTien.Text = "0";
                            lblPhuThu.Text = "0";
                            lblTongGiam.Text = "0";
                            reset();
                        }
                        else
                        {
                            if (!chk_print)
                                MessageBox.Show("Không tìm thấy máy in", "Print Err");

                            // Hiện report tĩnh khi không có máy in.
                            //Tạo label thông báo report đang chạy
                            lblReportLoading = new Label();
                            lblReportLoading.Text = "Đang khởi tạo báo cáo...";
                            lblReportLoading.Font = new Font("Arial", 30);
                            lblReportLoading.ForeColor = Color.Blue;
                            lblReportLoading.AutoSize = true;
                            lblReportLoading.BackColor = Color.Black;
                            lblReportLoading.Location = new Point(1024 / 2 - 250, 768 / 2);
                            this.Controls.Add(lblReportLoading);
                            lblReportLoading.BringToFront();

                            Thread objTheard = new Thread(ShowReportPay);
                            objTheard.IsBackground = true;
                            objTheard.Start();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }

        private void ShowReportPay(object obj)
        {
            try
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    Report.frmReport rp = new Report.frmReport();
                    rp.action = 2;
                    rp.id_order = id_order;
                    rp.Show();
                });
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Invoke((MethodInvoker)delegate() { this.Controls.Remove(lblReportLoading); });
            }
        }

        void prtDocument_PrintPage(object sender, PrintPageEventArgs e) // Phương thức định nghĩa trang in của Tính tiền / Tạm tính
        {
            Graphics gp = e.Graphics; // Khai báo 1 đối tượng hình ảnh.

            int startX = 1; // Định nghĩa lề trái của nội dung
            int startY = 5; // Định nghĩa lề trên của nội dung
            int offset = 18;// Định nghĩa bề dày của nội dung

            Font font = new System.Drawing.Font("Courier New", 10); // Định nghĩa font
            Brush brush = new SolidBrush(Color.Black); // Định nghĩa brush ( liên quan về màu chữ, nét chữ, ... )

            DataTable tbl = new DataTable(); // Bảng chứa dữ liệu của orderdetail
            DataTable tbl2 = new DataTable(); // Bảng chứa dữ liệu của orderdetail2

            tbl = Order_pro_DA.GetlistOrder_pro(id_order);
            tbl2 = Order_pro_DA.GetlistOrder2_pro(id_order);

            DataTable tblCompany = new DataTable(); // Bảng chứa dữ liệu của bảng company
            tblCompany = Company_DA.getcompany();

            //Xét sự tồn tại của đường dần logo trong bảng company
            if (System.IO.File.Exists(Application.StartupPath + "\\" + Account_DA.companyLogo))
            {
                // Draw logo ra bill
                Image i = Image.FromFile(Application.StartupPath + "\\" + Account_DA.companyLogo);
                gp.DrawImage(i, 75, 0, 150, 150);
                offset += 110;
            }

            gp.DrawString(tblCompany.Rows[0]["Companyname"].ToString(), new System.Drawing.Font("Courier New", 12), brush, startX + 10, startY + offset);
            offset += 20;
            gp.DrawString("Địa chỉ: " + tblCompany.Rows[0]["Address"].ToString(), font, brush, startX, startY + offset);
            offset += 30;
            gp.DrawString("MST: " + tblCompany.Rows[0]["Tax"].ToString(), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("ĐT: " + tblCompany.Rows[0]["Phone"].ToString(), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("HÓA ĐƠN TÍNH TIỀN", new System.Drawing.Font("Courier New", 12, FontStyle.Bold), brush, startX + 40, startY + offset);
            DataTable tbl_fn = new DataTable();
            if (tbl.Rows.Count > 0)
                tbl_fn = tbl;
            else
                tbl_fn = tbl2;
            offset += 30;
            gp.DrawString("HD Số: " + tbl_fn.Rows[0]["id"].ToString().PadRight(10) + "Bàn: " + (fastbuy?" ___" : tbl_fn.Rows[0]["Nametable"].ToString()), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("Ngày: " + tbl_fn.Rows[0]["Orderdate"].ToString(), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("NV: " + tbl_fn.Rows[0]["Fullname"].ToString(), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("KH: " + (tbl_fn.Rows[0]["Fullname1"].ToString() == "" ? "  ____" : tbl_fn.Rows[0]["Fullname1"].ToString()), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("--------------------------------", font, brush, startX, startY + offset);
            offset += 20;
            foreach (DataRow row in tbl.Rows)
            {
                string s = "               ";
                string product = "";
                decimal cost = (decimal)row["Price"];
                product = row["Name"].ToString();
                if (product.Length < 15)
                {
                    product += s.Substring(0, s.Length - product.Length);
                }
                else if (product.Length > 15)
                {
                    product = product.Substring(0, 12) + "...";
                }
                string productline = product.PadRight(10) + ("x" + row["Amount"].ToString()).PadLeft(5) + cost.ToString("N0").PadLeft(12);
                gp.DrawString(productline, font, brush, startX, startY + offset);
                offset += 18;
            }
            foreach (DataRow row in tbl2.Rows)
            {
                string s = "               ";
                string product = "";
                decimal cost = (decimal)row["Price"];
                product = row["Name"].ToString();
                if (product.Length < 15)
                {
                    product += s.Substring(0, s.Length - product.Length);
                }
                else if (product.Length > 15)
                {
                    product = product.Substring(0, 12) + "...";
                }
                string productline = product.PadRight(15) + ("x" + row["Amount"].ToString()) + cost.ToString("N0").PadLeft(12);
                gp.DrawString(productline, font, brush, startX, startY + offset);
                offset += 18;
            }
            gp.DrawString("--------------------------------", font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("".PadRight(5) + "Giảm giá: ".PadLeft(10) + ((decimal)tbl_fn.Rows[0]["total_discount"]).ToString("N0").PadLeft(17), font, brush, startX, startY + offset);
            offset += 20;
            gp.DrawString("".PadRight(5) + "Phụ thu: ".PadLeft(10) + ((decimal)tbl_fn.Rows[0]["total_surcharge"]).ToString("N0").PadLeft(17), font, brush, startX, startY + offset);
            offset += 20;

            if (typePay == "pay")
                gp.DrawString("".PadRight(5) + "Tổng cộng: ".PadLeft(10) + ((decimal)tbl_fn.Rows[0]["total_price"]).ToString("N0").PadLeft(16), new System.Drawing.Font("Courier New", 10, FontStyle.Bold), brush, startX, startY + offset);
            else

                gp.DrawString("".PadRight(5) + "Tạm tính: ".PadLeft(10) + ((decimal)tbl_fn.Rows[0]["total_price"]).ToString("N0").PadLeft(17), new System.Drawing.Font("Courier New", 10, FontStyle.Bold), brush, startX, startY + offset);
            offset += 40;
            gp.DrawString("Cám ơn quý khách! ", font, brush, startX + 55, startY + offset);
            offset += 20;
            gp.DrawString("", font, brush, startX + 40, startY + offset);
        }

        string typePay = ""; // Biến xác định kiểu thanh toán ( pay: tính tiền / temp: tạm tính )

        private void lblTempPay_Click(object sender, EventArgs e)
        {
            typePay = "temp";

            try
            {
                if (lstOrder.Items.Count == 0 && id_order == "")
                    MessageBox.Show("Chưa order món ăn");
                else
                {
                    if (MessageBox.Show("Bạn muốn tạm tính tiền bàn này không?", "Pay", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        if (id_order == "")
                        {
                            lblIn_Click(sender, e);
                        }
                        bool chk_print = false, chk_queue = false;
                        PrintDocument prtDocument = new PrintDocument();
                        if (lstOrder.Items.Count > 0)
                        {
                            prtDocument.PrintPage += prtDocument_PrintPage;
                            prtDocument.PrinterSettings.PrinterName = Print_DA.findNameprinterbyID(Company_DA.getcompany().Rows[0]["printbill"].ToString());
                            //prtDocument.DefaultPageSettings.PaperSize = new PaperSize("Custom", 280, 630);
                            foreach (string item in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                            {
                                if (item == prtDocument.PrinterSettings.PrinterName)
                                {
                                    chk_print = true;

                                    //Kiểm tra dữ liệu in có nằm trong queue chưa được in không
                                    PrintQueue queues = null;
                                    PrintServer printserver = new PrintServer();
                                    queues = printserver.GetPrintQueue(prtDocument.PrinterSettings.PrinterName);
                                    if (queues.NumberOfJobs > 0)
                                    {
                                        MessageBox.Show("Lỗi máy in " + prtDocument.PrinterSettings.PrinterName + ", in không thành công", "Err");
                                        chk_queue = false;
                                    }
                                    else
                                    {
                                        chk_queue = true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            chk_print = true; chk_queue = true;
                        }
                        if (chk_print && chk_queue)
                        {
                            if (lstOrder.Items.Count > 0)
                                prtDocument.Print();
                        }
                        else
                        {
                            if (!chk_print)
                                MessageBox.Show("Không tìm thấy máy in", "Err");

                            //Tạo label thông báo report đang chạy
                            lblReportLoading = new Label();
                            lblReportLoading.Text = "Đang khởi tạo báo cáo...";
                            lblReportLoading.Font = new Font("Arial", 30);
                            lblReportLoading.ForeColor = Color.Blue;
                            lblReportLoading.AutoSize = true;
                            lblReportLoading.BackColor = Color.Black;
                            lblReportLoading.Location = new Point(1024 / 2 - 250, 768 / 2);
                            this.Controls.Add(lblReportLoading);
                            lblReportLoading.BringToFront();

                            Thread objTheard = new Thread(ShowReportPay);
                            objTheard.IsBackground = true;
                            objTheard.Start();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
        Report.frmReport rp = null;
        Label lblReportLoading = null;
        /// <summary>
        /// Mở report báo cáo ca
        /// </summary>
        private void ShowReportShifts()
        {
            try
            {
            if (rp == null || rp.IsDisposed)
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    rp = new Report.frmReport();
                    rp.action = 1;
                    rp.id_order = id_order;
                    rp.Show();
                });
               
            }
            else
                rp.Activate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Invoke((MethodInvoker)delegate() { this.Controls.Remove(lblReportLoading); });
                
            }
        }
        private void lblReportShifts_Click(object sender, EventArgs e) // Sự kiện click nút Báo cáo ca.
        {

            //Tạo label thông báo report đang chạy
            lblReportLoading=new Label();
            lblReportLoading.Text = "Đang khởi tạo báo cáo...";
            lblReportLoading.Font = new Font("Arial", 30);
            lblReportLoading.ForeColor = Color.Blue;
            lblReportLoading.AutoSize = true;
            lblReportLoading.BackColor = Color.Black;
            lblReportLoading.Location = new Point(1024/2-250,768/2);
            this.Controls.Add(lblReportLoading);
            lblReportLoading.BringToFront();

            Thread objTheard = new Thread(ShowReportShifts);
            objTheard.IsBackground = true;
            objTheard.Start();

        }
        string id_menu = ""; // biến để xóa trên listview
        private void lblDelProducts_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.SelectedItems.Count == 0)
                {
                    MessageBox.Show("Chưa chọn món", "Err");
                }
                else if (MessageBox.Show("Bạn muốn hủy món này không?", "Ask", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    decimal cost = 0;
                    cost = Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) * Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text);



                    if (lstOrder.SelectedItems[0].Group.Name == "1")
                    {

                        lstProductCancel.Add(lstOrder.SelectedItems[0].Text + "|" + lstOrder.SelectedItems[0].SubItems[3].Text + "|" + lstOrder.SelectedItems[0].SubItems[1].Text + "|" + lstOrder.SelectedItems[0].SubItems[4].Text);
                        lblIn.Tag = "CancelProducts";
                    }


                    lstOrder.Items.RemoveAt(lstOrder.SelectedItems[0].Index);
                    //lblTongTien.Text = (Convert.ToDecimal(lblTongTien.Text) - cost).ToString("N0");
                    chkTru = false;
                    tinhtong();
                    id_menu = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        List<string> lstProductCancel = new List<string>();
        private void Cancel() // Phương thức in xuống bếp, khi hủy món ăn đã order
        {
            // Xử lý in xuống bếp hủy order
            List<string> listnameprinter = new List<string>();
            List<string> listvalueprint = new List<string>();

            // Tạo danh sách tên máy in, và nội dung in.
            foreach (string ls in lstProductCancel)
            {
                string getNameprinter = Print_DA.findNameprinterbyID(Categories_DA.findCategoryByCategoryID(Groupitems_DA.findCategoryByGroupitem(Menu_DA.findGroupitemByMenu(ls.Split('|')[1]))));

                if (getNameprinter == "")
                    getNameprinter = Print_DA.findNameprinterbyID(Company_DA.getcompany().Rows[0]["printbill"].ToString());

                if (listnameprinter.Count > 0)
                {
                    int printCount = listnameprinter.Count;
                    for (int i = 0; i < printCount; i++)
                    {
                        if (getNameprinter == listnameprinter[i])
                        {
                            for (int v = 0; v < listvalueprint.Count; v++)
                            {
                                if (listvalueprint[v].Split('|')[0] == getNameprinter)
                                {
                                    listvalueprint[v] += "|" + ls.Split('|')[0] + "/" + ls.Split('|')[2];
                                }
                            }
                            break;
                        }
                        else
                        {
                            listnameprinter.Add(getNameprinter);
                            listvalueprint.Add(getNameprinter + "|" + ls.Split('|')[0] + "/" + ls.Split('|')[2]);
                        }
                    }
                }
                else
                {
                    listnameprinter.Add(getNameprinter);
                    listvalueprint.Add(getNameprinter + "|" + ls.Split('|')[0] + "/" + ls.Split('|')[2]);
                }

                if (!chkTru)
                {
                    //xóa trong csdl
                    if (ls.Split('|')[3] == "0")
                    {
                        TinhDinhLuong1(Convert.ToInt32(ls.Split('|')[1]), Convert.ToInt32(ls.Split('|')[2]));
                        Orderdetails_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[1]);
                        Orderdetails_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[1]);

                    }
                    else
                    {
                        Orderdetail2s_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[0]);
                    }
                    Order_pro_DA.UpdateOrder_pro_totalprice(Convert.ToDecimal(lblTongTien.Text), id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblPhuThu.Text));
                }
                else
                {
                    int amount = Convert.ToInt32(ls.Split('|')[4]);
                    if (Convert.ToInt32(ls.Split('|')[4]) > 0)
                    {
                        amount = Convert.ToInt32(ls.Split('|')[4]) - Convert.ToInt32(ls.Split('|')[2]);
                        if (ls.Split('|')[3] == "0")
                        {
                            TinhDinhLuong1(Convert.ToInt32(id_menu), Convert.ToInt32(ls.Split('|')[2]));
                            Orderdetails_pro_DA.update_pro_amount(id_order, ls.Split('|')[1], Convert.ToInt32(ls.Split('|')[2]));
                        }
                        else
                            Orderdetail2s_pro_DA.update_pro_amount(id_order, ls.Split('|')[0], ls.Split('|')[2]);
                    }
                    if (amount == 0)
                    {
                        if (ls.Split('|')[3] == "0")
                        {
                            TinhDinhLuong1(Convert.ToInt32(id_menu), Convert.ToInt32(ls.Split('|')[2]));
                            Orderdetails_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[1]);
                            Orderdetails_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[1]);
                        }
                        else
                            Orderdetail2s_pro_DA.DeleteProducts_pro(id_order, ls.Split('|')[0]);

                    }

                    Order_pro_DA.UpdateOrder_pro_totalprice(Convert.ToDecimal(lblTongTien.Text), id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblPhuThu.Text));
                }
            }

            lstProductCancel.Clear();//reset
            bool chkPrin = false, chkqueue = false; // Biến kiểm tra tồn tại của máy in
            foreach (string s in listvalueprint) // In
            {
                PrintDocument prt = new PrintDocument();

                foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                {
                    if (s.Split('|')[0] == printer)
                    {
                        prt.PrinterSettings.PrinterName = s.Split('|')[0];
                        valuePrint = s;
                        prt.PrintPage += print_page_cancelOrder;

                        prt.Print();

                        //Kiểm tra dữ liệu in có nằm trong queue chưa được in không
                        PrintQueue queues = null;
                        PrintServer printserver = new PrintServer();
                        queues = printserver.GetPrintQueue(s.Split('|')[0]);
                        if (queues.NumberOfJobs > 0)
                        {
                            MessageBox.Show("Lỗi máy in " + s.Split('|')[0] + ", in không thành công", "Err");
                            chkqueue = false;
                        }
                        else
                        {
                            chkqueue = true;
                        }

                        chkPrin = true;
                        break;
                    }
                }
                if (!chkPrin)
                    MessageBox.Show("Không tìm thấy máy in " + s.Split('|')[0], "Err");
                else
                {
                    // Ghi vào nhật ký
                    string menuName = "";
                    for (int i = 1; i < valuePrint.Split('|').Length; i++)
                    {
                        menuName += valuePrint.Split('|')[i].Split('/')[0] + ", ";
                    }
                    string str = "Nhân viên " + Account_DA.staffName + " đã hủy món: " + menuName + " của bàn " + lblBan.Text + " - khu vực " + flowLayoutPanel3.Controls.Find(id_place, true)[0].Text;
                    Diary_DA.Insert(Account_DA.staff_ID, str, DateTime.Now);
                }
            }


            lblIn.Tag = "";

        }
        private void lblDelOrder_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.Groups[0].Items.Count > 0)
                {
                    MessageBox.Show("Hóa đơn đã gọi món chưa thanh toán, không hủy được", "Err");
                }
                else if (lstOrder.Groups[1].Items.Count > 0)
                {
                    lstOrder.Items.Clear();
                    lblTongGiam.Text = "0";
                    lblTongTien.Text = "0";
                    lblPhuThu.Text = "0";
                }
                else
                    MessageBox.Show("Bàn chưa được chọn hoặc chưa có order", "Thông báo5");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lstOrder_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            try
            {
                if (thaydoi == true)
                {
                    id_menu = lstOrder.Items[e.ItemIndex].SubItems[3].Text.ToString();
                }
                else
                    lstOrder.Items[e.ItemIndex].Selected = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TinhDinhLuong(int id, int value)
        {
            Formulas_DA.GetListFormulas(id);
            foreach (DataRow r in Formulas_DA.ListFormulas.Rows)
            {
                Materials_DA.GetListMaterial(r[0].ToString());
                if (r[2].ToString() == Materials_DA.ListMaterial.Rows[0][2].ToString())
                {
                    Materials_DA.UpdateMaterial(Materials_DA.ListMaterial.Rows[0][0].ToString(), Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) - (Convert.ToDecimal(r[1]) * value));
                }
                else
                {
                    Units_DA.GetListUnit(Materials_DA.ListMaterial.Rows[0][2].ToString());
                    do
                    {
                        if (Units_DA.ListUnit.Rows[0][2].ToString() == r[2].ToString())
                        {
                            Materials_DA.UpdateMaterial(Materials_DA.ListMaterial.Rows[0][0].ToString(), Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) - ((Convert.ToDecimal(r[1]) / Convert.ToDecimal(Units_DA.ListUnit.Rows[0][3])) * value));
                            break;
                        }
                        else
                        {
                            if (Units_DA.ListUnit.Rows.Count > 0)
                                Units_DA.GetListUnit(Units_DA.ListUnit.Rows[0][2].ToString());
                            else
                            {
                                MessageBox.Show("Không thể chuyển đổi định lượng trong công thức số: " + r[3].ToString(), "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                                break;
                            }
                        }
                    } while (true);
                }
            }

        }

        private void TinhDinhLuong1(int id, int value)
        {
            Formulas_DA.GetListFormulas(id);
            foreach (DataRow r in Formulas_DA.ListFormulas.Rows)
            {
                Materials_DA.GetListMaterial(r[0].ToString());
                if (r[2].ToString() == Materials_DA.ListMaterial.Rows[0][2].ToString())
                {
                    Materials_DA.UpdateMaterial(Materials_DA.ListMaterial.Rows[0][0].ToString(), Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) + (Convert.ToDecimal(r[1]) * value));
                }
                else
                {
                    Units_DA.GetListUnit(Materials_DA.ListMaterial.Rows[0][2].ToString());
                    do
                    {
                        if (Units_DA.ListUnit.Rows[0][2].ToString() == r[2].ToString())
                        {
                            Materials_DA.UpdateMaterial(Materials_DA.ListMaterial.Rows[0][0].ToString(), Convert.ToDecimal(Materials_DA.ListMaterial.Rows[0][1]) + ((Convert.ToDecimal(r[1]) / Convert.ToDecimal(Units_DA.ListUnit.Rows[0][3])) * value));
                            break;
                        }
                        else
                        {
                            if (Units_DA.ListUnit.Rows.Count > 0)
                                Units_DA.GetListUnit(Units_DA.ListUnit.Rows[0][2].ToString());
                            else
                            {
                                MessageBox.Show("Không thể chuyển đổi định lượng trong công thức số: " + r[3].ToString(), "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                                break;
                            }
                        }
                    } while (true);
                }
            }

        }

        private void lblIn_Click(object sender, EventArgs e)
        {
            //Xử lý in xuống bếp
            // {
            try
            {
                if (lblIn.Tag == "CancelProducts")
                {
                    Cancel();
                }

                if (lstOrder.Groups[1].Items.Count > 0)
                {
                    List<string> listnameprinter = new List<string>();
                    List<string> listvalueprint = new List<string>();

                    foreach (ListViewItem a in lstOrder.Groups[1].Items) // Tạo danh sách tên máy in, và nội dung in.
                    {
                        string getNameprinter = Print_DA.findNameprinterbyID(Categories_DA.findCategoryByCategoryID(Groupitems_DA.findCategoryByGroupitem(Menu_DA.findGroupitemByMenu(a.SubItems[3].Text))));

                        if (getNameprinter == "")
                            getNameprinter = Print_DA.findNameprinterbyID(Company_DA.getcompany().Rows[0]["printbill"].ToString());

                        if (listnameprinter.Count > 0)
                        {
                            int printCount = listnameprinter.Count;
                            for (int i = 0; i < printCount; i++)
                            {
                                if (getNameprinter == listnameprinter[i])
                                {
                                    for (int v = 0; v < listvalueprint.Count; v++)
                                    {
                                        if (listvalueprint[v].Split('|')[0] == getNameprinter)
                                        {
                                            listvalueprint[v] += "|" + a.Text + "/" + a.SubItems[1].Text + "/" + a.SubItems["NoteMenu"].Text;
                                        }
                                    }
                                    break;
                                }
                                else
                                {
                                    listnameprinter.Add(getNameprinter);
                                    listvalueprint.Add(getNameprinter + "|" + a.Text + "/" + a.SubItems[1].Text + "/" + a.SubItems["NoteMenu"].Text);
                                }
                            }
                        }
                        else
                        {
                            listnameprinter.Add(getNameprinter);
                            listvalueprint.Add(getNameprinter + "|" + a.Text + "/" + a.SubItems[1].Text + "/" + a.SubItems["NoteMenu"].Text);
                        }
                    }
                    bool chkPrin = false, chkqueue = false; // Biến kiểm tra tồn tại của máy in
                    foreach (string s in listvalueprint) // In
                    {
                        PrintDocument prt = new PrintDocument();

                        foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                        {
                            if (s.Split('|')[0] == printer)
                            {
                                prt.PrinterSettings.PrinterName = s.Split('|')[0];
                                valuePrint = s;
                                prt.PrintPage += prt_PrintPage;

                                prt.Print();
                                //Kiểm tra dữ liệu in có nằm trong queue chưa được in không
                                PrintQueue queues = null;
                                PrintServer printserver = new PrintServer();
                                queues = printserver.GetPrintQueue(s.Split('|')[0]);
                                if (queues.NumberOfJobs > 0)
                                {
                                    MessageBox.Show("Lỗi máy in " + s.Split('|')[0] + ", in không thành công", "Err");
                                    chkqueue = false;
                                }
                                else
                                {
                                    chkqueue = true;
                                }

                                chkPrin = true;
                                break;
                            }
                        }
                        if (!chkPrin)
                            MessageBox.Show("Không tìm thấy máy in " + s.Split('|')[0], "Err");
                    }
                    // }

                    if (lstOrder.Groups[0].Items.Count == 0 && lstOrder.Groups[1].Items.Count > 0 && (fastbuy || id_order == "")) //Nếu là bàn mới gọi món lần đầu
                    {
                        if (discount_type != "0")
                        {
                            if (id_discount != "")
                            {
                                Discounts_DA.UpdateDiscount(id_discount, discount_type, discount_value);
                                Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                            else
                            {
                                Discounts_DA.InsertDiscount(discount_type, discount_value);
                                id_discount = Discounts_DA.GetMaxDiscount();
                                Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                        }

                        //id_discount = Discounts_DA.GetMaxDiscount();
                        Order_pro_DA.InsertOrder_pro(null, Account_DA.staff_ID, id_ban!=0?id_ban.ToString():null, id_surcharge == "" ? null : id_surcharge, id_discount == "" ? null : id_discount, DateTime.Now, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                        id_order = Order_pro_DA.GetMaxOrder_pro();
                        foreach (ListViewItem a in lstOrder.Groups[1].Items)
                        {
                            if (a.SubItems[3].Text != "0")
                            {
                                Orderdetails_pro_DA.InsertOrderdetails_pro(id_order, a.SubItems[3].Text, Convert.ToDecimal(a.SubItems[4].Text), Convert.ToDecimal(a.SubItems[2].Text), a.SubItems[1].Text);
                                TinhDinhLuong(Convert.ToInt32(a.SubItems[3].Text), Convert.ToInt32(a.SubItems[1].Text));
                            }
                            else
                                Orderdetail2s_pro_DA.InsertOrderdetail2s_pro(id_order, a.Text, Convert.ToDecimal(a.SubItems[2].Text), a.SubItems[1].Text);
                        }

                        if (!fastbuy) // nếu bán nhanh thì không cần update bàn
                        {
                            Table_DA.updatetable(id_ban);
                            color = Color.DodgerBlue;
                            flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor = Color.SkyBlue;
                        }
                        // Ghi vào nhật ký
                        //string menuName = "";
                        //foreach (ListViewItem item in lstOrder.Groups[1].Items)
                        //{
                        //    menuName += item.Text + ", ";
                        //}
                        //string s = "Nhân viên " + Account_DA.staffName + " đã đặt món: " + menuName + " cho bàn " + lblBan.Text + " - khu vực " + flowLayoutPanel3.Controls.Find(id_place, true)[0].Text;
                        //Diary_DA.Insert(Account_DA.staff_ID, s, DateTime.Now);

                    }
                    else if ((lstOrder.Groups[0].Items.Count > 0 || id_order != "") && lstOrder.Groups[1].Items.Count > 0)
                    {
                        if (discount_type != "0")
                        {
                            if (id_discount != "")
                            {
                                Discounts_DA.UpdateDiscount(id_discount, discount_type, discount_value);
                                Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                            else
                            {
                                Discounts_DA.InsertDiscount(discount_type, discount_value);
                                id_discount = Discounts_DA.GetMaxDiscount();
                                Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                        }


                        foreach (ListViewItem a in lstOrder.Groups[1].Items)
                        {
                            bool them = true;
                            if (a.SubItems[3].Text != "0")
                            {
                                foreach (ListViewItem b in lstOrder.Groups[0].Items)
                                {
                                    if (a.SubItems[3].Text == b.SubItems[3].Text && b.SubItems[4].Text == "0")
                                    {
                                        Orderdetails_pro_DA.UpdateOrderdetails_pro_Amout(id_order, b.SubItems[3].Text, (Convert.ToInt16(b.SubItems[1].Text) + Convert.ToInt16(a.SubItems[1].Text)).ToString());
                                        them = false;
                                        break;
                                    }
                                }
                                if (them == true)
                                    Orderdetails_pro_DA.InsertOrderdetails_pro(id_order, a.SubItems[3].Text, Convert.ToDecimal(a.SubItems[4].Text), Convert.ToDecimal(a.SubItems[2].Text), a.SubItems[1].Text);
                                TinhDinhLuong(Convert.ToInt32(a.SubItems[3].Text), Convert.ToInt32(a.SubItems[1].Text));
                            }
                            else
                            {
                                foreach (ListViewItem b in lstOrder.Groups[0].Items)
                                {
                                    if (a.Text == b.Text && b.SubItems[4].Text == "1" & a.SubItems[2].Text == b.SubItems[2].Text)
                                    {
                                        Orderdetail2s_pro_DA.UpdateOrderdetail2s_pro_Amout(b.SubItems[3].Text, (Convert.ToInt16(b.SubItems[1].Text) + Convert.ToInt16(a.SubItems[1].Text)).ToString());
                                        them = false;
                                        break;
                                    }
                                }
                                if (them == true)
                                    Orderdetail2s_pro_DA.InsertOrderdetail2s_pro(id_order, a.Text, Convert.ToDecimal(a.SubItems[4].Text), a.SubItems[1].Text);
                            }

                        }
                        foreach (ListViewItem a in lstOrder.Groups[0].Items)
                        {
                            if (a.SubItems[4].Text == "0")
                            {
                                Orderdetails_pro_DA.UpdateOrderdetails_pro_Price(id_order, a.SubItems[3].Text, Convert.ToDecimal(a.SubItems[2].Text));
                            }
                            else
                                Orderdetail2s_pro_DA.UpdateOrderdetail2s_pro_Price(a.SubItems[3].Text, a.Text, Convert.ToDecimal(a.SubItems[2].Text));
                            //Order_DA_pro.UpdateOrder_DiscountDetail(id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                        }

                        // Ghi vào nhật ký
                        //string menuName = "";
                        //foreach (ListViewItem item in lstOrder.Groups[1].Items)
                        //{
                        //    menuName += item.Text + ", ";
                        //}
                        //string s = "Nhân viên " + Account_DA.staffName + " đã đặt món: " + menuName + " cho bàn " + lblBan.Text + " - khu vực " + flowLayoutPanel3.Controls.Find(id_place, true)[0].Text;
                        //Diary_DA.Insert(Account_DA.staff_ID, s, DateTime.Now);
                    }
                    else
                    {
                        MessageBox.Show("Chưa chọn món");
                        return;
                    }

                    lstOrder.Items.Clear();
                    Orderdetails_pro_DA.GetListOrderdetails_pro(id_order);
                    if (Orderdetails_pro_DA.ListOrderdetails.Rows.Count > 0)
                    {
                        foreach (DataRow r in Orderdetails_pro_DA.ListOrderdetails.Rows)
                        {
                            ListViewItem a = new ListViewItem();

                            ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                            b.Text = r["Amount"].ToString();
                            ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                            ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                            f.Text = r["Price"].ToString();
                            if (r["Price2"].ToString() == r["Price"].ToString())
                            {
                                a.Text = r["Name"].ToString();
                                c.Text = Convert.ToDecimal(r["Price2"]).ToString("N0");
                            }
                            else
                            {
                                c.Text = Convert.ToDecimal(r["Price2"]).ToString("N0");
                                a.Text = "#" + r["Name"].ToString();
                            }
                            ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                            d.Text = r["ID"].ToString();
                            ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                            g.Text = "0";
                            a.SubItems.Add(b);
                            a.SubItems.Add(c);
                            a.SubItems.Add(d);
                            a.SubItems.Add(g);
                            a.SubItems.Add(f);
                            a.Group = lstOrder.Groups[0];
                            lstOrder.Items.Add(a);

                        }
                    }
                    Orderdetail2s_pro_DA.GetListOrderdetail2s_pro(id_order);
                    if (Orderdetail2s_pro_DA.ListOrderdetail2s.Rows.Count > 0)
                    {
                        foreach (DataRow r in Orderdetail2s_pro_DA.ListOrderdetail2s.Rows)
                        {
                            ListViewItem a = new ListViewItem();
                            a.Text = r["Productname"].ToString();
                            ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                            b.Text = r["Amount"].ToString();
                            ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                            c.Text = Convert.ToDecimal(r["Price"]).ToString("N0");
                            ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                            d.Text = r["ID"].ToString();
                            ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                            g.Text = "1";
                            ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                            f.Text = Convert.ToDecimal(r["Price"]).ToString("N0");
                            a.SubItems.Add(b);
                            a.SubItems.Add(c);
                            a.SubItems.Add(d);
                            a.SubItems.Add(g);
                            a.SubItems.Add(f);
                            a.Group = lstOrder.Groups[0];
                            lstOrder.Items.Add(a);
                        }
                    }
                    tinhtong();
                    Order_pro_DA.UpdateOrder_pro(id_order, id_customer == "" ? null : id_customer, Account_DA.staff_ID, id_ban != 0 ? id_ban.ToString() : null, id_surcharge == "" || surcharge_type == "2" ? null : id_surcharge, id_discount == "" ? null : id_discount, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void prt_PrintPage(object sender, PrintPageEventArgs e) // In order xuống bếp
        {
            Graphics gp = e.Graphics;
            int startX = 5, startY = 5, offset = 18;
            Font font = new System.Drawing.Font("Courier New", 10);
            Brush brush = new SolidBrush(Color.Black);
            string s = "               ";
            gp.DrawString("ĐẶT MÓN", new System.Drawing.Font("Courier New", 13), brush, startX + 50, startY);
            gp.DrawString(DateTime.Now.ToString(), font, brush, startX, startY + offset + 18);
            offset += 36;
            gp.DrawString("Bàn: " + (this.Controls.Find("B" + id_ban.ToString(), true).Length > 0 ? this.Controls.Find("B" + id_ban.ToString(), true)[0].Text : "   ___").PadRight(10) + "Khu vực: " + (this.Controls.Find(id_place == "" ? "0" : id_place, true).Length > 0 ? this.Controls.Find(id_place == "" ? "0" : id_place, true)[0].Text : "   ___"), font, brush, startX, startY + offset);
            offset += 18;
            gp.DrawString("------------------------", font, brush, startX, startY + offset);
            offset += 20;
            for (int i = 1; i < valuePrint.Split('|').Length; i++)
            {
                string product = "", amount = "", note = "";
                product = valuePrint.Split('|')[i].Split('/')[0];
                if (product.Length < 15)
                {
                    product += s.Substring(0, s.Length - product.Length);
                }
                else if (product.Length > 15)
                {
                    product = product.Substring(0, 12) + "...";
                }
                amount = valuePrint.Split('|')[i].Split('/')[1];
                note = valuePrint.Split('|')[i].Split('/')[2];
                gp.DrawString(product.PadRight(18) + amount.PadRight(5) + note, font, brush, startX, startY + offset);
                offset += 18;
            }
        }
        private void print_page_cancelOrder(object sender, PrintPageEventArgs e)
        {
            Graphics gp = e.Graphics;
            int startX = 5, startY = 5, offset = 18;
            Font font = new System.Drawing.Font("Courier New", 10);
            Brush brush = new SolidBrush(Color.Black);
            string s = "               ";
            gp.DrawString("HỦY MÓN", new System.Drawing.Font("Courier New", 13), brush, startX + 50, startY);
            gp.DrawString(DateTime.Now.ToString(), font, brush, startX, startY + offset + 18);
            offset += 36;
            gp.DrawString("Bàn: " + (this.Controls.Find("B" + id_ban.ToString(), true).Length > 0 ? this.Controls.Find("B" + id_ban.ToString(), true)[0].Text : "   ___").PadRight(10) + "Khu vực: " + (this.Controls.Find(id_place, true).Length > 0 ? this.Controls.Find(id_place, true)[0].Text : "   ___"), font, brush, startX, startY + offset);
            offset += 18;
            gp.DrawString("------------------------", font, brush, startX, startY + offset);
            offset += 20;
            for (int i = 1; i < valuePrint.Split('|').Length; i++)
            {
                string product = "", amount = "";
                product = valuePrint.Split('|')[i].Split('/')[0];
                amount = valuePrint.Split('|')[i].Split('/')[1];
                gp.DrawString(product.PadRight(18) + amount, font, brush, startX, startY + offset);
                offset += 18;
            }
        }

        private void lblCong_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.SelectedItems.Count > 0)
                {
                    showKeyNum();
                    lblValTitle.Text = "Số lượng cần tăng";
                    type_txtvalue = "Cong";
                    txtValue.Text = "1";
                    txtValue.Focus();
                }
                else
                    MessageBox.Show("Chưa chọn món", "Thông báo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        bool chkTru = false; // Xác định khi click vào nút trừ ( để thực hiện in hủy món )
        private void lblTru_Click(object sender, EventArgs e)
        {
            try
            {

                if (lstOrder.SelectedItems.Count > 0)
                {
                    showKeyNum();
                    lblValTitle.Text = "Số lượng cần giảm";
                    type_txtvalue = "Tru";
                    txtValue.Text = "1";
                    txtValue.Focus();
                }
                else
                    MessageBox.Show("Chưa chọn món", "Thông báo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblDiscountPercent_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.Items.Count > 0)
                {
                    if (id_customer != "" || discount_value != "0")
                    {
                        if (MessageBox.Show("Hóa đơn này đã có giảm giá, bạn muốn thay đổi không?", "Err", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            lblValTitle.Text = "Nhập giá trị % cần giảm";
                            txtValue.MaxLength = 3;
                            type_txtvalue = "DP";
                            //showKeyboard();
                            showKeyNum();
                            txtValue.Text = "";
                            txtValue.Focus();
                        }
                    }
                    else
                    {
                        lblValTitle.Text = "Nhập giá trị % cần giảm";
                        txtValue.MaxLength = 3;
                        type_txtvalue = "DP";
                        //showKeyboard();
                        showKeyNum();
                        txtValue.Text = "";
                        txtValue.Focus();
                    }

                }
                else
                    MessageBox.Show("Chưa chọn bàn để giảm");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void showKeyNum()
        {
            if (this.Controls.ContainsKey("keynum"))
                this.Controls.Find("keynum", true)[0].Visible = true;
            else
            {
                KeyNum Num = new KeyNum();
                Num.Name = "keynum";
                Num.Location = new Point(txtValue.Location.X + txtValue.Width - Num.Width, txtValue.Location.Y + txtValue.Height);
                Num.VisibleChanged += keynumd_VisibleChanged;
                this.Controls.Add(Num);
                Num.BringToFront();
            }
        }

        private void lblDiscountValue_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.Items.Count > 0)
                {
                    if (id_customer != "" || discount_value != "0")
                    {
                        if (MessageBox.Show("Hóa đơn này đã có giảm giá, bạn muốn thay đổi không?", "Err", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            lblValTitle.Text = "Nhập giá trị tiền cần giảm";
                            txtValue.MaxLength = 8;
                            txtValue.Text = "";
                            txtValue.Focus();
                            type_txtvalue = "DV";
                            //showKeyboard();
                            showKeyNum();
                        }
                    }
                    else
                    {
                        lblValTitle.Text = "Nhập giá trị tiền cần giảm";
                        txtValue.MaxLength = 8;
                        txtValue.Text = "";
                        type_txtvalue = "DV";
                        //showKeyboard();
                        showKeyNum();
                        txtValue.Focus();
                    }
                }
                else
                    MessageBox.Show("Chưa chọn bàn để giảm");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblDiscountPercentDetail_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.SelectedItems.Count > 0)
                {
                    bool chk = false;
                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) != "#")
                    {
                        chk = true;
                    }
                    else if (!chk_discount)
                    {
                        if (MessageBox.Show("Món này đã có giảm giá, bạn muốn thay đổi không?", "Err", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            chk = true;
                        }
                    }
                    else
                        MessageBox.Show("Món ăn này đang có chương trình khuyến mãi, không được thay đổi", "Err");

                    if (chk)
                    {
                        lblValTitle.Text = "Nhập giá trị phần trăm cần giảm";
                        txtValue.Text = "";
                        txtValue.Focus();
                        type_txtvalue = "DPD";
                        // showKeyboard();
                        showKeyNum();
                        txtValue.MaxLength = 3;
                        thaydoi = false;
                    }
                }
                else
                {
                    MessageBox.Show("Chưa chọn món để giảm giá");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblDiscountValueDetail_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.SelectedItems.Count > 0)
                {
                    bool chk = false;
                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) != "#")
                    {
                        chk = true;
                    }
                    else if (!chk_discount)
                    {
                        if (MessageBox.Show("Món này đã có giảm giá, bạn muốn thay đổi không?", "Err", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            chk = true;
                        }
                    }
                    else
                        MessageBox.Show("Món ăn này đang có chương trình khuyến mãi, không được thay đổi", "Err");
                    if (chk)
                    {
                        lblValTitle.Text = "Nhập giá trị tiền cần giảm";
                        type_txtvalue = "DVD";
                        //showKeyboard();
                        showKeyNum();
                        txtValue.Text = "";
                        txtValue.MaxLength = 8;
                        txtValue.Focus();
                        thaydoi = false;
                    }

                }
                else
                {
                    MessageBox.Show("Chưa chọn món để giảm giá");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        bool chk = false;

        private void tinhtong()
        {
            decimal tonggia = 0, giagoc = 0, giagiam = 0, phuthu = 0, tonggia2 = 0, giagoc2 = 0;

            if (value_customer != "" || discount_value != "" || surcharge_value != "")
            {
                foreach (ListViewItem a in lstOrder.Items)
                {
                    if (a.Group.Name == "1")
                    {
                        if (a.Text.Substring(0, 1) != "#")
                        {
                            tonggia += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                            tonggia2 += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                        }
                        else
                        {
                            giagiam += (Convert.ToDecimal(a.SubItems[5].Text) - Convert.ToDecimal(a.SubItems[2].Text)) * Convert.ToDecimal(a.SubItems[1].Text);
                            giagoc += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                            giagoc2 += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                        }
                    }
                    if (a.Group.Name == "2")
                    {
                        if (a.Text.Substring(0, 1) != "#")
                        {
                            tonggia += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                        }
                        else
                        {
                            giagiam += (Convert.ToDecimal(a.SubItems[4].Text) - Convert.ToDecimal(a.SubItems[2].Text)) * Convert.ToDecimal(a.SubItems[1].Text);
                            giagoc += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                        }
                    }
                }
                if (value_customer != "")
                {
                    lblTongGiam.Text = ((tonggia * Convert.ToDecimal(value_customer) * (decimal)0.01) + giagiam).ToString("N0");
                    lblTongTien.Text = ((tonggia * (100 - Convert.ToDecimal(value_customer)) * (decimal)0.01) + giagoc).ToString("N0");
                }
                else if (discount_type == "1")
                {
                    lblTongGiam.Text = ((tonggia * Convert.ToDecimal(discount_value) * (decimal)0.01) + giagiam).ToString("N0");
                    lblTongTien.Text = ((tonggia * (100 - Convert.ToDecimal(discount_value)) * (decimal)0.01) + giagoc).ToString("N0");
                }
                else if (discount_type == "2")
                {
                    lblTongGiam.Text = (Convert.ToDecimal(discount_value) + giagiam).ToString("N0");
                    lblTongTien.Text = Convert.ToDecimal((tonggia + giagoc) - Convert.ToDecimal(discount_value)).ToString("N0");
                }
                else
                {
                    lblTongGiam.Text = (giagiam).ToString("N0");
                    lblTongTien.Text = Convert.ToDecimal(tonggia + giagoc).ToString("N0");
                }
                if (surcharge_type == "1" && lblPhuThu.Text == "0")
                {
                    phuthu_old = (tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01;
                    lblPhuThu.Text = Convert.ToDecimal(phuthu_old).ToString("N0");
                    lblTongTien.Text = Convert.ToDecimal(Convert.ToDecimal(lblTongTien.Text) + Convert.ToDecimal(lblPhuThu.Text)).ToString("N0");
                }
                else if (surcharge_type == "1" && lblPhuThu.Text != "0")
                {
                    if (id_order != "")
                    {
                        string value = Order_pro_DA.FindSurcharge_pro(id_order);
                        if (value != "")
                        {
                            if (phuthu_old == 0)
                            {
                                phuthu_old = Convert.ToDecimal((tonggia2 + giagoc2) * Convert.ToDecimal(value) * (decimal)0.01);
                            }
                            phuthu = Convert.ToDecimal(lblPhuThu.Text) - phuthu_old;
                            phuthu_old = Convert.ToDecimal((tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01);
                            lblPhuThu.Text = Convert.ToDecimal(((tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01) + phuthu).ToString("N0");
                        }
                        else
                        {
                            lblPhuThu.Text = Convert.ToDecimal(((tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01) + Convert.ToDecimal(lblPhuThu.Text)).ToString("N0");
                        }

                    }
                    else
                    {
                        phuthu = Convert.ToDecimal(lblPhuThu.Text) - phuthu_old;
                        phuthu_old = Convert.ToDecimal((tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01);
                        lblPhuThu.Text = Convert.ToDecimal(((tonggia + giagoc) * Convert.ToDecimal(surcharge_value) * (decimal)0.01) + phuthu).ToString("N0");
                    }
                    lblTongTien.Text = Convert.ToDecimal(Convert.ToDecimal(lblTongTien.Text) + Convert.ToDecimal(lblPhuThu.Text)).ToString("N0");
                }
                else
                {
                    lblPhuThu.Text = (Convert.ToDecimal(surcharge_value) + Convert.ToDecimal(lblPhuThu.Text)).ToString("N0");
                    lblTongTien.Text = (Convert.ToDecimal(lblTongTien.Text) + Convert.ToDecimal(lblPhuThu.Text)).ToString("N0");
                }
            }
            else
            {
                foreach (ListViewItem a in lstOrder.Items)
                {
                    tonggia += Convert.ToDecimal(a.SubItems[2].Text) * Convert.ToDecimal(a.SubItems[1].Text);
                }
                lblTongGiam.Text = "0";
                lblTongTien.Text = tonggia.ToString("N0");
                lblPhuThu.Text = "0";
            }
        }

        private void txtValue_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    if (type_txtvalue == "DP")
                    {
                        if (string.IsNullOrEmpty(txtValue.Text))
                        {
                            MessageBox.Show("Chưa nhập giá trị", "Thông báo");
                        }
                        else
                        {
                            long i = Convert.ToInt64(txtValue.Text);
                            if (i < 100)
                            {
                                discount_value = txtValue.Text;
                                discount_type = "1";
                                tinhtong();
                                if (lstOrder.Groups[1].Items.Count == 0)
                                {
                                    if (id_discount != "")
                                    {
                                        Discounts_DA.UpdateDiscount(id_discount, "1", txtValue.Text);
                                        Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                    }
                                    else
                                    {
                                        Discounts_DA.InsertDiscount("1", txtValue.Text);
                                        Order_pro_DA.UpdateOrder_pro_Discount(id_order, Discounts_DA.GetMaxDiscount(), Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                    }

                                }
                                txtValue.MaxLength = 500;
                                lblValTitle.Text = "Tìm món ăn";
                                txtValue.Text = "";
                                type_txtvalue = "findMenu";
                                this.Controls.Find("keynum", true)[0].Visible = false;
                            }
                            else
                                MessageBox.Show("Phần trăm không được quá 100", "Thông báo");
                        }
                    }
                    else if (type_txtvalue == "DV")
                    {
                        if (string.IsNullOrEmpty(txtValue.Text))
                        {
                            MessageBox.Show("Chưa nhập giá trị", "Thông báo");
                        }
                        else
                        {
                            long i = Convert.ToInt64(txtValue.Text);
                            if (i < Convert.ToDecimal(lblTongTien.Text))
                            {
                                //chk = true;
                                discount_value = txtValue.Text;
                                discount_type = "2";
                                tinhtong();
                                if (lstOrder.Groups[1].Items.Count == 0)
                                {
                                    if (id_discount != "")
                                    {
                                        Discounts_DA.UpdateDiscount(id_discount, "2", txtValue.Text);
                                        Order_pro_DA.UpdateOrder_pro_Discount(id_order, id_discount, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                    }
                                    else
                                    {
                                        Discounts_DA.InsertDiscount("2", txtValue.Text);
                                        Order_pro_DA.UpdateOrder_pro_Discount(id_order, Discounts_DA.GetMaxDiscount(), Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                    }

                                }
                                txtValue.MaxLength = 500;
                                lblValTitle.Text = "Tìm món ăn";
                                txtValue.Text = "";
                                type_txtvalue = "findMenu";
                                this.Controls.Find("keynum", true)[0].Visible = false;
                            }
                            else
                            {
                                MessageBox.Show("Số tiền giảm vượt quá giá hóa đơn");
                                //this.Controls.Find("keyboard", true)[0].Visible = false;
                                thaydoi = true;
                            }
                        }
                    }
                    else if (type_txtvalue == "DPD")
                    {
                        if (string.IsNullOrEmpty(txtValue.Text))
                        {
                            MessageBox.Show("Chưa nhập giá trị", "Thông báo");
                        }
                        else
                        {
                            long i = Convert.ToInt64(txtValue.Text);
                            if (i <= 100)
                            {
                                //chk = true;
                                if (txtValue.Text != "0")
                                {
                                    lstOrder.SelectedItems[0].SubItems[2].Text = (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[5].Text) * ((decimal)100 - Convert.ToDecimal(txtValue.Text)) * (decimal)0.01).ToString("N0");
                                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) != "#")
                                        lstOrder.SelectedItems[0].Text = "#" + lstOrder.SelectedItems[0].Text;
                                }
                                else
                                {
                                    lstOrder.SelectedItems[0].SubItems[2].Text = lstOrder.SelectedItems[0].SubItems[5].Text;
                                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) == "#")
                                        lstOrder.SelectedItems[0].Text = lstOrder.SelectedItems[0].Text.Remove(0, 1);
                                }
                                tinhtong();

                                if (lstOrder.Groups[1].Items.Count == 0)
                                {
                                    if (lstOrder.SelectedItems[0].SubItems[4].Text == "0")
                                    {
                                        Orderdetails_pro_DA.UpdateOrderdetails_pro_Price(id_order, id_menu, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                        Orderdetails_pro_DA.UpdateOrderdetails_pro_Price(id_order, id_menu, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                    }
                                    else
                                        Orderdetail2s_pro_DA.UpdateOrderdetail2s_pro_Price(lstOrder.SelectedItems[0].SubItems[3].Text, lstOrder.SelectedItems[0].Text, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                    Order_pro_DA.UpdateOrder_pro_DiscountDetail(id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                }

                                txtValue.MaxLength = 500;
                                lblValTitle.Text = "Tìm món ăn";
                                txtValue.Text = "";
                                type_txtvalue = "findMenu";
                                this.Controls.Find("keynum", true)[0].Visible = false;
                                thaydoi = true;
                            }
                            else
                                MessageBox.Show("Phần trăm không được quá 100", "Thông báo");
                        }
                    }
                    else if (type_txtvalue == "DVD")
                    {
                        if (string.IsNullOrEmpty(txtValue.Text))
                        {
                            MessageBox.Show("Chưa nhập giá trị", "Thông báo");
                        }
                        else
                        {
                            long i = Convert.ToInt64(txtValue.Text);
                            if (i <= Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text))
                            {
                                //chk = true;
                                if (txtValue.Text != "0")
                                {
                                    lstOrder.SelectedItems[0].SubItems[2].Text = (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[5].Text) - Convert.ToDecimal(txtValue.Text)).ToString("N0");
                                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) != "#")
                                        lstOrder.SelectedItems[0].Text = "#" + lstOrder.SelectedItems[0].Text;
                                }
                                else
                                {
                                    lstOrder.SelectedItems[0].SubItems[2].Text = lstOrder.SelectedItems[0].SubItems[5].Text;
                                    if (lstOrder.SelectedItems[0].Text.Substring(0, 1) == "#")
                                        lstOrder.SelectedItems[0].Text = lstOrder.SelectedItems[0].Text.Remove(0, 1);
                                }
                                tinhtong();
                                if (lstOrder.Groups[1].Items.Count == 0)
                                {
                                    if (lstOrder.SelectedItems[0].SubItems[4].Text == "0")
                                    {
                                        Orderdetails_pro_DA.UpdateOrderdetails_pro_Price(id_order, id_menu, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                        Orderdetails_pro_DA.UpdateOrderdetails_pro_Price(id_order, id_menu, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                    }
                                    else
                                        Orderdetail2s_pro_DA.UpdateOrderdetail2s_pro_Price(lstOrder.SelectedItems[0].SubItems[3].Text, lstOrder.SelectedItems[0].Text, Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text));
                                    Order_pro_DA.UpdateOrder_pro_DiscountDetail(id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                                }

                                thaydoi = true;
                                txtValue.MaxLength = 500;
                                lblValTitle.Text = "Tìm món ăn";
                                txtValue.Text = "";
                                type_txtvalue = "findMenu";
                                this.Controls.Find("keynum", true)[0].Visible = false;
                            }
                            else
                            {
                                MessageBox.Show("Số tiền giảm vượt quá giá món ăn");
                                this.Controls.Find("keynum", true)[0].Visible = false;
                                thaydoi = true;
                            }
                        }
                    }
                    else if (type_txtvalue == "C")
                    {
                        //chk = true;
                        Custome_DA.findCustomer(txtValue.Text);
                        if (Custome_DA.ListCustomer.Rows.Count > 0)
                        {
                            id_customer = txtValue.Text;
                            value_customer = Custome_DA.ListCustomer.Rows[0][5].ToString();
                            tinhtong();
                            if (lstOrder.Groups[1].Items.Count == 0)
                            {
                                Order_pro_DA.UpdateOrder_pro_Customer(id_order, id_customer, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                            txtValue.MaxLength = 500;
                            lblValTitle.Text = "Tìm món ăn";
                            txtValue.Text = "";
                            type_txtvalue = "findMenu";
                            this.Controls.Find("keyboard", true)[0].Visible = false;
                        }
                        else
                        {
                            MessageBox.Show("Mã khách hàng không tồn tại", "Err");
                            chk = false;
                        }
                    }
                    else if (type_txtvalue == "SC")
                    {
                        if (string.IsNullOrEmpty(txtValue.Text))
                        {
                            MessageBox.Show("Chưa nhập giá trị", "Thông báo");
                        }
                        else
                        {
                            long i = Convert.ToInt64(txtValue.Text);
                            //chk = true;
                            surcharge_value = txtValue.Text;
                            surcharge_type = "2";
                            tinhtong();
                            if (lstOrder.Groups[1].Items.Count == 0)
                            {
                                Order_pro_DA.UpdateOrder_pro_surcharge2(id_order, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                            }
                            txtValue.MaxLength = 500;
                            lblValTitle.Text = "Tìm món ăn";
                            txtValue.Text = "";
                            type_txtvalue = "findMenu";
                            this.Controls.Find("keynum", true)[0].Visible = false;
                        }
                    }
                    else if (type_txtvalue == "OthermenuInput")
                    {
                        chk = false;
                        if (lblBan.Text != "")
                        {
                            if (!string.IsNullOrEmpty(txtValue.Text))
                            {
                                othermenuInput = txtValue.Text;
                                this.Controls.Find("keyboard", true)[0].Visible = false;
                                lblValTitle.Text = "Nhập đơn giá";
                                txtValue.Focus();
                                showKeyNum();
                                txtValue.Text = "";
                                type_txtvalue = "othermenuInputPrice";
                            }
                            else
                                MessageBox.Show("Chưa nhập tên món ăn", "Err");
                        }
                        else
                            MessageBox.Show("Chưa chọn bàn", "Thông báo");
                    }
                    else if (type_txtvalue == "othermenuInputPrice")
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(txtValue.Text))
                            {
                                int i = Convert.ToInt32(txtValue.Text);
                                if (i > 0)
                                {
                                    othermenuInput += "|" + txtValue.Text;
                                    lblValTitle.Text = "Nhập số lượng";
                                    txtValue.Text = "";
                                    type_txtvalue = "othermenuInputAmount";
                                }
                                else
                                    MessageBox.Show("Đơn giá phải lớn hơn 0", "Err");
                            }
                            else
                                MessageBox.Show("Chưa nhập đơn giá", "Err");
                        }
                        catch
                        {
                        }
                    }
                    else if (type_txtvalue == "othermenuInputAmount")
                    {
                        chk = false;
                        try
                        {
                            if (!string.IsNullOrEmpty(txtValue.Text))
                            {
                                int i = Convert.ToInt32(txtValue.Text);
                                if (i > 0)
                                {
                                    if (lstOrder.Groups[1].Items.Count == 0)
                                    {
                                        ListViewItem a = new ListViewItem();
                                        ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem h = new ListViewItem.ListViewSubItem();
                                        a.Name = "othermenu";
                                        a.Text = othermenuInput.Split('|')[0];
                                        h.Name = "NoteMenu";
                                        h.Text = "";
                                        b.Text = Convert.ToDecimal(othermenuInput.Split('|')[1]).ToString("N0");

                                        //b.Text = Convert.ToDateTime(othermenuInput.Split('|')[1]).ToString("N0");

                                        c.Text = txtValue.Text;
                                        d.Text = "0";
                                        g.Text = othermenuInput.Split('|')[1];
                                        f.Text = othermenuInput.Split('|')[1];
                                        a.SubItems.Add(c);
                                        a.SubItems.Add(b);
                                        a.SubItems.Add(d);
                                        a.SubItems.Add(g);
                                        a.SubItems.Add(f);
                                        a.SubItems.Add(h);
                                        a.Group = lstOrder.Groups[1];
                                        lstOrder.Items.Add(a);
                                        lblTongTien.Text = (Convert.ToDecimal(lblTongTien.Text) + (Convert.ToDecimal(b.Text) * Convert.ToDecimal(c.Text))).ToString("N0");
                                    }
                                    else
                                    {
                                        bool them = true;
                                        foreach (ListViewItem item in lstOrder.Groups[1].Items)
                                        {
                                            if (item.Text == othermenuInput.Split('|')[0] & item.SubItems[2].Text == Convert.ToDecimal(othermenuInput.Split('|')[1]).ToString("N0"))
                                            {
                                                item.SubItems[1].Text = (Convert.ToInt16(item.SubItems[1].Text) + Convert.ToInt16(txtValue.Text)).ToString();
                                                them = false;
                                                break;
                                            }
                                        }
                                        if (them)
                                        {
                                            ListViewItem a = new ListViewItem();
                                            ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                            ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                            ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                            ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                            ListViewItem.ListViewSubItem f = new ListViewItem.ListViewSubItem();
                                            ListViewItem.ListViewSubItem h = new ListViewItem.ListViewSubItem();
                                            h.Name = "NoteMenu";
                                            h.Text = "";
                                            a.Name = "othermenu";
                                            a.Text = othermenuInput.Split('|')[0];
                                            b.Text = Convert.ToDecimal(othermenuInput.Split('|')[1]).ToString("N0");
                                            c.Text = txtValue.Text;
                                            d.Text = "0";
                                            g.Text = othermenuInput.Split('|')[1];
                                            f.Text = othermenuInput.Split('|')[1];
                                            a.SubItems.Add(c);
                                            a.SubItems.Add(b);
                                            a.SubItems.Add(d);
                                            a.SubItems.Add(g);
                                            a.SubItems.Add(f);
                                            a.SubItems.Add(h);
                                            a.Group = lstOrder.Groups[1];
                                            lstOrder.Items.Add(a);
                                            lblTongTien.Text = (Convert.ToDecimal(lblTongTien.Text) + (Convert.ToDecimal(b.Text) * Convert.ToDecimal(c.Text))).ToString("N0");
                                        }
                                    }
                                    lblValTitle.Text = "Tìm món ăn";
                                    txtValue.Text = "";
                                    type_txtvalue = "findMenu";
                                    this.Controls.Find("keynum", true)[0].Visible = false;
                                }
                                else
                                    MessageBox.Show("Số lượng phải lớn hơn 0", "Err");
                            }
                            else
                                MessageBox.Show("Chưa nhập số lượng", "Err");
                        }
                        catch
                        {

                        }
                    }
                    else if (type_txtvalue == "NoteMenu")
                    {
                        chk = true;
                        lstOrder.SelectedItems[0].SubItems["NoteMenu"].Text = txtValue.Text;
                        this.Controls.Find("keyboard", true)[0].Visible = false;
                        MessageBox.Show("Đã thêm ghi chú " + txtValue.Text);
                        lblValTitle.Text = "Tìm món ăn";
                        txtValue.Text = "";
                        type_txtvalue = "findMenu";
                    }
                    else if (type_txtvalue == "Tru")
                    {
                        if (Convert.ToInt32(txtValue.Text) > Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text))
                        {
                            MessageBox.Show("Vượt quá số lượng cho phép.", "Thông báo");
                        }
                        else
                        {
                            if (lstOrder.SelectedItems[0].Group.Name == "1")
                            {
                                if (lstProductCancel.Count > 0)
                                {
                                    bool chk = false;
                                    for (int i = 0; i < lstProductCancel.Count; i++)
                                    {
                                        if (lstOrder.SelectedItems[0].SubItems[3].Text == lstProductCancel[i].Split('|')[1])
                                        {
                                            lstProductCancel[i] = lstProductCancel[i].Split('|')[0] + "|" + lstProductCancel[i].Split('|')[1] + "|" + (Convert.ToInt32(lstProductCancel[i].Split('|')[2]) + Convert.ToInt32(txtValue.Text)).ToString() + "|" + lstProductCancel[i].Split('|')[3] + "|" + lstProductCancel[i].Split('|')[4];
                                            chk = true;
                                            break;
                                        }
                                    }
                                    if (!chk)
                                        lstProductCancel.Add(lstOrder.SelectedItems[0].Text + "|" + lstOrder.SelectedItems[0].SubItems[3].Text + "|" + txtValue.Text + "|" + lstOrder.SelectedItems[0].SubItems[4].Text + "|" + lstOrder.SelectedItems[0].SubItems[1].Text);
                                }
                                else
                                {
                                    lstProductCancel.Add(lstOrder.SelectedItems[0].Text + "|" + lstOrder.SelectedItems[0].SubItems[3].Text + "|" + txtValue.Text + "|" + lstOrder.SelectedItems[0].SubItems[4].Text + "|" + lstOrder.SelectedItems[0].SubItems[1].Text);
                                }

                                lblIn.Tag = "CancelProducts";

                            }

                            decimal cost = 0;
                            cost = Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) * Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[2].Text);

                            if (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) > 0)
                            {
                                lstOrder.SelectedItems[0].SubItems[1].Text = (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) - Convert.ToInt32(txtValue.Text)).ToString();
                            }
                            if (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) == 0)
                            {
                                lstOrder.SelectedItems[0].Remove();
                            }

                            chkTru = true;
                            this.Controls.Find("keynum", true)[0].Visible = false;
                            lblValTitle.Text = "Tìm món ăn";
                            txtValue.Text = "";
                            type_txtvalue = "findMenu";
                            tinhtong();
                        }
                    }
                    else if (type_txtvalue == "Cong")
                    {
                        if (lstOrder.SelectedItems[0].Group.Name == "2")
                        {
                            if (KiemTraDinhLuong(Convert.ToInt32(lstOrder.SelectedItems[0].SubItems[3].Text), Convert.ToInt32(lstOrder.SelectedItems[0].SubItems[1].Text) + Convert.ToInt32(txtValue.Text)))
                            {
                                lstOrder.SelectedItems[0].SubItems[1].Text = (Convert.ToDecimal(lstOrder.SelectedItems[0].SubItems[1].Text) + Convert.ToInt32(txtValue.Text)).ToString();
                                tinhtong();
                            }
                        }
                        else
                        {
                            if (lstOrder.Groups[1].Items.Count == 0)
                            {
                                if (KiemTraDinhLuong(Convert.ToInt32(lstOrder.SelectedItems[0].SubItems[3].Text), Convert.ToInt32(txtValue.Text)))
                                {
                                    ListViewItem a = new ListViewItem();
                                    a.Text = lstOrder.SelectedItems[0].Text;
                                    ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                    b.Text = txtValue.Text;
                                    ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                    c.Text = lstOrder.SelectedItems[0].SubItems[2].Text;
                                    ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                    if (lstOrder.SelectedItems[0].SubItems[4].Text == "1")
                                    { d.Text = "0"; }
                                    else d.Text = lstOrder.SelectedItems[0].SubItems[3].Text;
                                    ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                    ListViewItem.ListViewSubItem h = new ListViewItem.ListViewSubItem();
                                    h.Name = "NoteMenu";
                                    h.Text = "";
                                    g.Text = lstOrder.SelectedItems[0].SubItems[5].Text;
                                    a.SubItems.Add(b);
                                    a.SubItems.Add(c);
                                    a.SubItems.Add(d);
                                    a.SubItems.Add(g);
                                    a.SubItems.Add(h);
                                    a.Group = lstOrder.Groups[1];
                                    lstOrder.Items.Add(a);
                                    tinhtong();
                                }
                            }
                            else
                            {
                                bool them = true;
                                foreach (ListViewItem item in lstOrder.Groups[1].Items)
                                {
                                    if (item.Text == lstOrder.SelectedItems[0].Text)
                                    {
                                        them = false;
                                        if (KiemTraDinhLuong(Convert.ToInt32(lstOrder.SelectedItems[0].SubItems[3].Text), Convert.ToInt32(item.SubItems[1].Text) + Convert.ToInt32(txtValue.Text)))
                                        {
                                            item.SubItems[1].Text = (Convert.ToDecimal(item.SubItems[1].Text) + Convert.ToInt32(txtValue.Text)).ToString();
                                            tinhtong();
                                            break;
                                        }
                                    }
                                }
                                if (them)
                                {
                                    if (KiemTraDinhLuong(Convert.ToInt32(lstOrder.SelectedItems[0].SubItems[3].Text), Convert.ToInt32(txtValue.Text)))
                                    {
                                        ListViewItem a = new ListViewItem();
                                        a.Text = lstOrder.SelectedItems[0].Text;
                                        ListViewItem.ListViewSubItem b = new ListViewItem.ListViewSubItem();
                                        b.Text = "1";
                                        ListViewItem.ListViewSubItem c = new ListViewItem.ListViewSubItem();
                                        c.Text = lstOrder.SelectedItems[0].SubItems[2].Text;
                                        ListViewItem.ListViewSubItem d = new ListViewItem.ListViewSubItem();
                                        if (lstOrder.SelectedItems[0].SubItems[4].Text == "1")
                                        { d.Text = "0"; }
                                        else d.Text = lstOrder.SelectedItems[0].SubItems[3].Text;
                                        ListViewItem.ListViewSubItem g = new ListViewItem.ListViewSubItem();
                                        ListViewItem.ListViewSubItem h = new ListViewItem.ListViewSubItem();
                                        h.Name = "NoteMenu";
                                        h.Text = "";
                                        g.Text = lstOrder.SelectedItems[0].SubItems[5].Text;
                                        a.SubItems.Add(b);
                                        a.SubItems.Add(c);
                                        a.SubItems.Add(d);
                                        a.SubItems.Add(g);
                                        a.SubItems.Add(h);
                                        a.Group = lstOrder.Groups[1];
                                        lstOrder.Items.Add(a);
                                        tinhtong();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        string othermenuInput = ""; // biến chứa giá trị món ăn khác.

        private void lblCancelTables_Click(object sender, EventArgs e)
        {
            try
            {
                if (id_order != "")
                {
                    MessageBox.Show("Hóa đơn đã gọi món chưa thanh toán, không hủy được", "Err");
                }
                else if (lstOrder.Groups[1].Items.Count > 0)
                {
                    lstOrder.Items.Clear();
                    lblTongGiam.Text = "0";
                    lblTongTien.Text = "0";
                    lblPhuThu.Text = "0";
                    lblValTitle.Text = "Tìm món ăn";
                    type_txtvalue = "findMenu";
                    txtValue.Text = "";
                    flowLayoutPanel3.Controls.Find(nameTable, true)[0].BackColor = Color.DarkGreen;
                    reset();
                }
                else if (lblBan.Text != "")
                {
                    lblBan.Text = "";
                    lblValTitle.Text = "Tìm món ăn";
                    type_txtvalue = "findMenu";
                    txtValue.Text = "";
                    flowLayoutPanel3.Controls.Find(nameTable, true)[0].BackColor = Color.DarkGreen;
                }
                else
                    MessageBox.Show("Bàn chưa được chọn hoặc chưa có order", "Thông báo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void reset()
        {
            name = "";
            id_order = "";
            id_table = "";
            //id_place = "";
            type_txtvalue = "";
            valuePrint = "";
            oldtable = "";
            newtable = "";
            place = "";
            discount_value = "0";
            discount_type = "0";
            surcharge_value = "0";
            surcharge_type = "0";
            value_customer = "";
            id_customer = "";
            id_discount = "";
            id_surcharge = "";
            sumtotalsurcharge = 0;
            thaydoi = true;
            phuthu_old = 0;
            total_surcharge = 0;
            txtValue.Text = "";
            lblValTitle.Text = "Tìm món ăn";
            type_txtvalue = "findMenu";
            lblBan.Text = "";
            nameTable = "";
        }
        bool chk_surcharge = false; // Kiểm tra khi đã click vô nút phụ thu
        private void lblSurcharge_Click(object sender, EventArgs e)
        {
            try
            {
                if (chk_surcharge)
                {
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Name != "lblCancelSwap" && ctrl.Name != "lblCancelCompile" && ctrl.Tag != null && ctrl.Tag.ToString() != "2" && ctrl.Tag.ToString() != "4")
                        {
                            ctrl.Visible = true;

                        }
                        else
                            ctrl.Visible = false;
                    }
                    flowLayoutPanel1.Controls.RemoveByKey("lblOther");

                    for (int i = 0; i < Surcharge_DAL.ListSurchargeReason.Rows.Count; i++)
                    {
                        Label lbl3 = new Label();
                        lbl3.Name = Surcharge_DAL.ListSurchargeReason.Rows[i]["id"].ToString();
                        lbl3.BackColor = Color.FromArgb(0, 192, 192);
                        lbl3.Text = Surcharge_DAL.ListSurchargeReason.Rows[i]["Reason"].ToString();
                        lbl3.Size = new Size(114, 70);
                        lbl3.Tag = Surcharge_DAL.ListSurchargeReason.Rows[i]["Rebateform"].ToString() + "/" + Surcharge_DAL.ListSurchargeReason.Rows[i]["Value"].ToString(); ;
                        lbl3.Font = new Font("Microsoft Sans Serif", 13);
                        lbl3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl3.TextAlign = ContentAlignment.MiddleCenter;
                        lbl3.Click += lbl_Click;
                        bool chk = false;
                        foreach (Control ctrl2 in flowLayoutPanel1.Controls)
                        {
                            if (ctrl2.Name == lbl3.Name && ctrl2.Tag != null && ctrl2.Name != "lblBack" && ctrl2.Name != "lblOther")
                            {
                                chk = true;
                                break;
                            }
                        }
                        if (!chk)
                        {
                            flowLayoutPanel1.Controls.Add(lbl3);
                        }
                    }
                    Label lbl2 = new Label();
                    lbl2.Name = "lblOther";
                    lbl2.BackColor = Color.FromArgb(0, 192, 192);
                    lbl2.Text = "Khác";
                    lbl2.Tag = "1";
                    lbl2.Size = new Size(114, 70);
                    lbl2.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl2.Font = new Font("Microsoft Sans Serif", 13);
                    lbl2.TextAlign = ContentAlignment.MiddleCenter;
                    lbl2.Click += lbl_Click;
                    flowLayoutPanel1.Controls.Add(lbl2);
                }
                else
                {
                    Surcharge_DAL.GetListSurcharge();
                    Label lbl = new Label();
                    lbl.Name = "lblBack";
                    lbl.BackColor = Color.Teal;
                    lbl.Text = "Quay lại";
                    lbl.Tag = "1";
                    lbl.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl.Size = new Size(114, 70);
                    lbl.Font = new Font("Microsoft Sans Serif", 13);
                    lbl.TextAlign = ContentAlignment.MiddleCenter;
                    lbl.Click += lbl_Click;
                    flowLayoutPanel1.Controls.Add(lbl);
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Tag == null)
                        {
                            ctrl.Visible = false;
                        }
                    }
                    for (int i = 0; i < Surcharge_DAL.ListSurchargeReason.Rows.Count; i++)
                    {
                        Label lbl3 = new Label();
                        lbl3.Name = Surcharge_DAL.ListSurchargeReason.Rows[i]["id"].ToString();
                        lbl3.BackColor = Color.FromArgb(0, 192, 192);
                        lbl3.Text = Surcharge_DAL.ListSurchargeReason.Rows[i]["Reason"].ToString();
                        lbl3.Size = new Size(114, 70);
                        lbl3.Tag = Surcharge_DAL.ListSurchargeReason.Rows[i]["Rebateform"].ToString() + "/" + Surcharge_DAL.ListSurchargeReason.Rows[i]["Value"].ToString(); ;
                        lbl3.Font = new Font("Microsoft Sans Serif", 13);
                        lbl3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl3.TextAlign = ContentAlignment.MiddleCenter;
                        lbl3.Click += lbl_Click;
                        flowLayoutPanel1.Controls.Add(lbl3);
                    }
                    Label lbl2 = new Label();
                    lbl2.Name = "lblOther";
                    lbl2.BackColor = Color.FromArgb(0, 192, 192);
                    lbl2.Text = "Khác";
                    lbl2.Tag = "1";
                    lbl2.Size = new Size(114, 70);
                    lbl2.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl2.Font = new Font("Microsoft Sans Serif", 13);
                    lbl2.TextAlign = ContentAlignment.MiddleCenter;
                    lbl2.Click += lbl_Click;
                    flowLayoutPanel1.Controls.Add(lbl2);
                }
                chk_surcharge = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void lbl_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Label)sender).Name == "lblBack")
                {
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Name != "lblCancelSwap" && ctrl.Name != "lblNoteMenu" && ctrl.Name != "lblBreakTable" && ctrl.Name != "lblReportShifts" && ctrl.Name != "lblFastBuy" && ctrl.Name != "lblCheckTable" && ctrl.Tag == null)
                        {
                            ctrl.Visible = true;
                        }
                        else
                            ctrl.Visible = false;
                    }
                }
                else if (((Label)sender).Name == "lblOther")
                {
                    if (id_order != "")
                    {
                        type_txtvalue = "SC";
                        lblValTitle.Text = "Nhập giá trị phụ thu";
                        //showKeyboard();
                        showKeyNum();
                        txtValue.Focus();
                    }
                    else
                        MessageBox.Show("Bàn chưa có order");
                }
                else
                {
                    if (id_order != "")
                    {
                        surcharge_type = ((Label)sender).Tag.ToString().Split('/')[0];
                        surcharge_value = ((Label)sender).Tag.ToString().Split('/')[1];
                        if (surcharge_type == "1")
                            id_surcharge = ((Label)sender).Name;
                        tinhtong();
                        if (lstOrder.Groups[1].Items.Count == 0)
                        {
                            if (id_surcharge != "")
                                Order_pro_DA.UpdateOrder_pro_surcharge(id_order, id_surcharge, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                            else
                                Order_pro_DA.UpdateOrder_pro_surcharge2(id_order, Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                        }
                    }
                    else
                        MessageBox.Show("Bàn chưa có order");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void showKeyboard()
        {
            if (this.Controls.ContainsKey("keyboard"))
            {
                this.Controls.Find("keyboard", true)[0].Visible = true;
            }
            else
            {
                DevComponents.DotNetBar.Keyboard.KeyboardControl keyboard = new DevComponents.DotNetBar.Keyboard.KeyboardControl();
                keyboard.Width = txtValue.Width;
                keyboard.Name = "keyboard";
                keyboard.IsTopBarVisible = false;
                keyboard.Height = 300;
                if (type_txtvalue == "findMenu")
                    keyboard.Location = new Point(6, 429);
                else
                    keyboard.Location = new Point(txtValue.Location.X, txtValue.Location.Y + txtValue.Height);
                keyboard.VisibleChanged += keyboard_VisibleChanged;
                this.Controls.Add(keyboard);
                keyboard.BringToFront();
            }
        }
        void keynumd_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                thaydoi = true;
                if (!((Control)sender).Visible)
                {
                    txtValue.Text = "";
                    first_load();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void keyboard_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                if (type_txtvalue == "findMenu")
                    ((Control)sender).Location = new Point(6, 429);
                else
                    ((Control)sender).Location = new Point(txtValue.Location.X, txtValue.Location.Y + txtValue.Height);
                //txtValue.Enabled = ((Control)sender).Visible;
                thaydoi = true;
                if (!((Control)sender).Visible)
                {
                    txtValue.Text = "";
                    first_load();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblRefeshMenu_Click(object sender, EventArgs e)
        {
            try
            {
                CreateMenu();
                GetTable();
                lstOrder.Items.Clear();
                lblTongGiam.Text = "0";
                lblTongTien.Text = "0";
                lblPhuThu.Text = "0";
                lblValTitle.Text = "Tìm món ăn";
                type_txtvalue = "findMenu";
                txtValue.Text = "";
                reset();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblLogout_Click(object sender, EventArgs e)
        {
            //Application.Restart();
            flogin.txtUsername.Text = "";
            flogin.txtPassword.Text = "";
            flogin.lblErr.Text = "";
            if (flogin.ShowDialog() == DialogResult.Yes)
            {
                chk_login = true;
            }
            else
            {
                chk_login = false;
            }
            frmMain_Load(sender, e);
        }
        bool chk_swap = false;
        private void lblSwapTable_Click(object sender, EventArgs e)
        {
            try
            {
                if (id_order != "")
                {
                    if (chk_swap)
                    {
                        foreach (Control ctrl in flowLayoutPanel1.Controls)
                        {
                            if (ctrl.Name != "lblCancelSwap")
                            {
                                ctrl.Visible = false;
                            }
                            else
                                ctrl.Visible = true;
                        }
                    }
                    else
                    {
                        foreach (Control ctrl in flowLayoutPanel1.Controls)
                        {
                            if (ctrl.Tag == null)
                            {
                                ctrl.Visible = false;
                            }
                        }
                        Label lbl = new Label();
                        lbl.Name = "lblCancelSwap";
                        lbl.BackColor = Color.Teal;
                        lbl.Text = "Hủy chuyển";
                        lbl.Tag = "1";
                        lbl.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl.Size = new Size(114, 70);
                        lbl.Font = new Font("Microsoft Sans Serif", 13);
                        lbl.TextAlign = ContentAlignment.MiddleCenter;
                        lbl.Click += lblCancelSwap;
                        flowLayoutPanel1.Controls.Add(lbl);
                    }

                    act = "Swaptable";
                    oldtable = flowLayoutPanel3.Controls[id_table].Text;
                    place = flowLayoutPanel3.Controls[id_place].Text;
                    flowLayoutPanel3.Controls[id_table].BackColor = Color.DarkSlateGray;
                    chk_swap = true;
                }
                else
                    MessageBox.Show("Chưa chọn bàn hoặc bàn chưa có order", "Err");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOrder.Items.Count > 0)
                {
                    if (id_customer != "" || discount_value != "0")
                    {
                        if (MessageBox.Show("Hóa đơn này đã có giảm giá, bạn muốn thay đổi không?", "Err", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            lblValTitle.Text = "Nhập mã khách hàng";
                            type_txtvalue = "C";
                            showKeyboard();
                            txtValue.Text = "";
                            txtValue.Focus();
                        }
                    }
                    else
                    {
                        lblValTitle.Text = "Nhập mã khách hàng";
                        txtValue.MaxLength = 3;
                        type_txtvalue = "C";
                        showKeyboard();
                        txtValue.Text = "";
                        txtValue.Focus();
                    }
                }
                else
                    MessageBox.Show("Bàn chưa có order");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void canSwap(bool chk)
        {

            foreach (Control ctrl in flowLayoutPanel1.Controls)
            {
                if (ctrl.Name != "lblCancelSwap" && ctrl.Name != "lblNoteMenu" && ctrl.Name != "lblBreakTable" && ctrl.Name != "lblReportShifts" && ctrl.Name != "lblFastBuy" && ctrl.Name != "lblCheckTable" && ctrl.Tag == null)
                {
                    ctrl.Visible = true;
                }
                else
                    ctrl.Visible = false;
            }
            act = "";
            if (!chk)
                flowLayoutPanel3.Controls[id_table].BackColor = Color.SkyBlue;
            else
                flowLayoutPanel3.Controls[id_table].BackColor = Color.DarkGreen;
            chk_swap = true;

        }
        private void lblCancelSwap(object sender, EventArgs e)
        {
            canSwap(false);
        }
        bool chk_compile = false;
        private void lblCompileTable_Click(object sender, EventArgs e)
        {
            try
            {
                if (id_order != "")
                {
                    if (chk_compile)
                    {
                        foreach (Control ctrl in flowLayoutPanel1.Controls)
                        {
                            if (ctrl.Name != "lblCancelCompile")
                            {
                                ctrl.Visible = false;
                            }
                            else
                                ctrl.Visible = true;
                        }
                    }
                    else
                    {
                        foreach (Control ctrl in flowLayoutPanel1.Controls)
                        {
                            if (ctrl.Tag == null)
                            {
                                ctrl.Visible = false;
                            }
                        }
                        Label lbl = new Label();
                        lbl.Name = "lblCancelCompile";
                        lbl.BackColor = Color.Teal;
                        lbl.Text = "Hủy gộp";
                        lbl.Tag = "1";
                        lbl.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl.Size = new Size(114, 70);
                        lbl.Font = new Font("Microsoft Sans Serif", 13);
                        lbl.TextAlign = ContentAlignment.MiddleCenter;
                        lbl.Click += lblCancelCompile;
                        flowLayoutPanel1.Controls.Add(lbl);
                    }

                    act = "Compile";
                    oldtable = flowLayoutPanel3.Controls[id_table].Text;
                    flowLayoutPanel3.Controls[id_table].BackColor = Color.DarkSlateGray;
                    place = flowLayoutPanel3.Controls[id_place].Text;
                    chk_compile = true;
                }
                else
                    MessageBox.Show("Chưa chọn bàn hoặc bàn chưa có order", "Err");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void cancelCompile(bool chk)
        {

            foreach (Control ctrl in flowLayoutPanel1.Controls)
            {
                if (ctrl.Name != "lblCancelCompile" && ctrl.Name != "lblNoteMenu" && ctrl.Name != "lblBreakTable" && ctrl.Name != "lblReportShifts" && ctrl.Name != "lblFastBuy" && ctrl.Name != "lblCheckTable" && ctrl.Tag == null)
                {
                    ctrl.Visible = true;
                }
                else
                    ctrl.Visible = false;
            }
            act = "";
            if (flowLayoutPanel3.Controls[id_table].BackColor == Color.DarkSlateGray && !chk)
                flowLayoutPanel3.Controls[id_table].BackColor = Color.SkyBlue;
            else
                flowLayoutPanel3.Controls[id_table].BackColor = Color.DarkGreen;
            chk_compile = true;
        }
        private void lblCancelCompile(object sender, EventArgs e)
        {
            cancelCompile(false);
        }

        private void txtValue_Click(object sender, EventArgs e)
        {
            if (type_txtvalue == "findMenu")
                showKeyboard();
        }

        private void lstOrder_DoubleClick(object sender, EventArgs e)
        {

        }

        private void lblPrinter_Click(object sender, EventArgs e)
        {
            SetupPrinter prtSetup = new SetupPrinter();
            prtSetup.Name = "prtSetup";
            prtSetup.Location = new Point(0, 0);
            this.Controls.Add(prtSetup);
            prtSetup.BringToFront();
        }

        private void txtValue_Leave(object sender, EventArgs e)
        {
            if (this.Controls.Find("Keyboard", true).Length > 0)
                this.Controls.Find("Keyboard", true)[0].Visible = false;
            if (this.Controls.ContainsKey("keynum"))
                this.Controls.Find("keynum", true)[0].Visible = false;
            pictureBox1.Visible = true;
            first_load();
        }

        private void txtValue_EnabledChanged(object sender, EventArgs e)
        {
            if (!txtValue.Enabled)
                pictureBox1.BackColor = SystemColors.Control;
            else
                pictureBox1.BackColor = Color.White;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            lblValTitle.Text = "Nhập món khác";
            type_txtvalue = "OthermenuInput";
            txtValue.Focus();
            if (this.Controls.Find("Keyboard", true).Length > 0)
                this.Controls.Find("Keyboard", true)[0].Visible = true;
            else
                showKeyboard();
        }

        private void txtValue_Enter(object sender, EventArgs e)
        {
            pictureBox1.Visible = false;
        }

        private void txtValue_TextChanged(object sender, EventArgs e)
        {
            if (type_txtvalue == "findMenu")
            {
                findMenu();

            }
        }

        private void findMenu()
        {
            if (txtValue.Text.Length > 0)
            {
                foreach (Control ctrl in flowLayoutPanel2.Controls)
                {
                    if (ctrl.Name.Substring(0, 2) == "TD" && (ctrl.Name.Substring(2) == txtValue.Text || ctrl.Text.Contains(txtValue.Text)))
                        flowLayoutPanel2.Controls[ctrl.Name].Visible = true;
                    else
                        flowLayoutPanel2.Controls[ctrl.Name].Visible = false;
                }
            }
            else
            {
                foreach (Control ctrl in flowLayoutPanel2.Controls)
                {
                    if (ctrl.Name.Substring(0, 2) != "TD" && ctrl.Name.Substring(0, 2) != "NH")
                        ctrl.Visible = true;
                    else
                        ctrl.Visible = false;
                }
            }
        }

        bool OtherClicked = true; // Biến để kiểm tra nhấn nút Khác chưa.
        private void lblOther_Click(object sender, EventArgs e) //Sự kiện nhấn nút khác (nút ...)
        {
            foreach (Label lbl in flowLayoutPanel1.Controls)
            {
                if (OtherClicked)
                {
                    if (lbl.Name != "lblOtherfunc" && lbl.Name != "lblBreakTable" && lbl.Name != "lblNoteMenu" && lbl.Name != "lblReportShifts" && lbl.Name != "lblFastBuy" && lbl.Name != "lblCheckTable")
                    {
                        lbl.Visible = false;
                    }
                    else
                    {
                        lbl.Visible = true;
                    }
                    lblOtherfunc.Margin = new Padding(0, 3, 0, 0);
                }
                else
                {
                    if (lbl.Name != "lblBreakTable" && lbl.Name != "lblNoteMenu" && lbl.Name != "lblReportShifts" && lbl.Name != "lblFastBuy" && lbl.Name != "lblCheckTable" && lbl.Tag == null)
                    {
                        lbl.Visible = true;
                    }
                    else
                        lbl.Visible = false;
                    lblOtherfunc.Margin = new Padding(3, 3, 0, 0);
                }
            }
            OtherClicked = !OtherClicked;
        }
        bool chk_notemenu = false; // Kiểm tra nhấn nút ghi chú món ăn.
        bool chk_chkTable = false; // Kiểm tra nhân nút kiểm tra bàn.
        private void lblNoteMenu_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable tbl = Notemenu_DA.getnotemenus();
                if (chk_notemenu)
                {
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Name != "lblCancelSwap" && ctrl.Name != "lblCancelCompile" && (string)ctrl.Tag == "2")
                        {
                            ctrl.Visible = true;
                        }
                        else
                            ctrl.Visible = false;
                    }
                    flowLayoutPanel1.Controls.RemoveByKey("lblOtherMenu");

                    for (int i = 0; i < tbl.Rows.Count; i++)
                    {
                        Label lbl3 = new Label();
                        lbl3.Name = tbl.Rows[i]["id"].ToString();
                        lbl3.BackColor = Color.FromArgb(0, 192, 192);
                        lbl3.Text = tbl.Rows[i]["Name"].ToString();
                        lbl3.Size = new Size(114, 70);
                        lbl3.Tag = "2";
                        lbl3.Font = new Font("Microsoft Sans Serif", 13);
                        lbl3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl3.TextAlign = ContentAlignment.MiddleCenter;
                        lbl3.Click += lblNotemenu_Click;
                        bool chk = false;
                        foreach (Control ctrl2 in flowLayoutPanel1.Controls)
                        {
                            if (ctrl2.Name == lbl3.Name && ctrl2.Tag != null && ctrl2.Name != "lblBack" && ctrl2.Name != "lblOtherMenu")
                            {
                                chk = true;
                                break;
                            }
                        }
                        if (!chk)
                        {
                            flowLayoutPanel1.Controls.Add(lbl3);
                        }
                    }
                    Label lbl2 = new Label();
                    lbl2.Name = "lblOtherMenu";
                    lbl2.BackColor = Color.FromArgb(0, 192, 192);
                    lbl2.Text = "Khác";
                    lbl2.Tag = "2";
                    lbl2.Size = new Size(114, 70);
                    lbl2.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl2.Font = new Font("Microsoft Sans Serif", 13);
                    lbl2.TextAlign = ContentAlignment.MiddleCenter;
                    lbl2.Click += lblNotemenu_Click;
                    flowLayoutPanel1.Controls.Add(lbl2);
                }
                else
                {
                    Label lbl = new Label();
                    lbl.Name = "lblBack";
                    lbl.BackColor = Color.Teal;
                    lbl.Text = "Quay lại";
                    lbl.Tag = "2";
                    lbl.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl.Size = new Size(114, 70);
                    lbl.Font = new Font("Microsoft Sans Serif", 13);
                    lbl.TextAlign = ContentAlignment.MiddleCenter;
                    lbl.Click += lblNotemenu_Click;
                    flowLayoutPanel1.Controls.Add(lbl);
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Tag == null)
                        {
                            ctrl.Visible = false;
                        }
                    }
                    for (int i = 0; i < Notemenu_DA.getnotemenus().Rows.Count; i++)
                    {
                        Label lbl3 = new Label();
                        lbl3.Name = tbl.Rows[i]["id"].ToString();
                        lbl3.BackColor = Color.FromArgb(0, 192, 192);
                        lbl3.Text = tbl.Rows[i]["Name"].ToString();
                        lbl3.Size = new Size(114, 70);
                        lbl3.Tag = "2";
                        lbl3.Font = new Font("Microsoft Sans Serif", 13);
                        lbl3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                        lbl3.TextAlign = ContentAlignment.MiddleCenter;
                        lbl3.Click += lblNotemenu_Click;
                        flowLayoutPanel1.Controls.Add(lbl3);
                    }
                    Label lbl2 = new Label();
                    lbl2.Name = "lblOtherMenu";
                    lbl2.BackColor = Color.FromArgb(0, 192, 192);
                    lbl2.Text = "Khác";
                    lbl2.Tag = "2";
                    lbl2.Size = new Size(114, 70);
                    lbl2.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                    lbl2.Font = new Font("Microsoft Sans Serif", 13);
                    lbl2.TextAlign = ContentAlignment.MiddleCenter;
                    lbl2.Click += lblNotemenu_Click;
                    flowLayoutPanel1.Controls.Add(lbl2);
                }
                chk_notemenu = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblNotemenu_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Label)sender).Name == "lblBack")
                {
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Name == "lblOtherfunc" | ctrl.Name == "lblNoteMenu" | ctrl.Name == "lblBreakTable" | ctrl.Name == "lblReportShifts" | ctrl.Name == "lblFastBuy" | ctrl.Name == "lblCheckTable")
                            ctrl.Visible = true;
                        else
                            ctrl.Visible = false;
                    }
                }
                else if (((Label)sender).Name == "lblOtherMenu")
                {
                    if (lstOrder.SelectedItems.Count > 0 && lstOrder.SelectedItems[0].Group.Name == "2")
                    {
                        type_txtvalue = "NoteMenu";
                        lblValTitle.Text = "Nhập ghi chú cho món ăn";
                        showKeyboard();
                        txtValue.Focus();
                    }
                    else
                        MessageBox.Show("Chưa chọn món hoặc món đã order");
                }
                else
                {
                    if (lstOrder.SelectedItems.Count > 0 && lstOrder.SelectedItems[0].Group.Name == "2")
                    {
                        lstOrder.SelectedItems[0].SubItems["NoteMenu"].Text = ((Label)sender).Text;
                        MessageBox.Show("Đã thêm ghi chú " + ((Label)sender).Text);
                    }
                    else
                        MessageBox.Show("Chưa chọn món hoặc món đã order");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lblBan_TextChanged(object sender, EventArgs e)
        {
            lstProductCancel.Clear();
        }

        private void lblCheckTable_Click(object sender, EventArgs e)
        {
            //Đếm số bàn có và trống
            int available = 0, notavailable = 0;
            foreach (Control ctrl in flowLayoutPanel3.Controls)
            {
                if (ctrl.Name.Substring(0, 1) == "B")
                    if (ctrl.BackColor == Color.DarkGreen || ctrl.BackColor == Color.DarkSeaGreen)
                        notavailable += 1;
                    else if (ctrl.BackColor == Color.DodgerBlue || ctrl.BackColor == Color.SkyBlue)
                        available += 1;
            }

            if (chk_chkTable)
            {
                foreach (Control ctrl in flowLayoutPanel1.Controls)
                {
                    if ((string)ctrl.Tag == "3")
                    {
                        ctrl.Visible = true;
                        if (ctrl.Name == "lblAvailableTable")
                            ctrl.Text = "Có Order (" + available.ToString() + ")";
                        if (ctrl.Name == "lblNotAvailableTable")
                            ctrl.Text = "Trống (" + notavailable.ToString() + ")";
                    }
                    else
                        ctrl.Visible = false;
                }
            }
            else
            {
                foreach (Control ctrl in flowLayoutPanel1.Controls)
                {
                    ctrl.Visible = false;
                }
                Label lbl = new Label();
                lbl.Name = "lblchecktbleCheck";
                lbl.BackColor = Color.Teal;
                lbl.Text = "Quay lại";
                lbl.Tag = "3";
                lbl.Size = new Size(114, 70);
                lbl.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                lbl.Font = new Font("Microsoft Sans Serif", 13);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                lbl.Click += lblchecktable_Click;
                flowLayoutPanel1.Controls.Add(lbl);

                Label lbl3 = new Label();
                lbl3.Name = "lblAvailableTable";
                lbl3.BackColor = Color.FromArgb(0, 192, 192);
                lbl3.Text = "Có Order (" + available.ToString() + ")";
                lbl3.Tag = "3";
                lbl3.Size = new Size(114, 70);
                lbl3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                lbl3.Font = new Font("Microsoft Sans Serif", 13);
                lbl3.TextAlign = ContentAlignment.MiddleCenter;
                lbl3.Click += lblchecktable_Click;
                flowLayoutPanel1.Controls.Add(lbl3);

                Label lbl2 = new Label();
                lbl2.Name = "lblNotAvailableTable";
                lbl2.BackColor = Color.FromArgb(0, 192, 192);
                lbl2.Text = "Trống (" + notavailable.ToString() + ")";
                lbl2.Tag = "3";
                lbl2.Size = new Size(114, 70);
                lbl2.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
                lbl2.Font = new Font("Microsoft Sans Serif", 13);
                lbl2.TextAlign = ContentAlignment.MiddleCenter;
                lbl2.Click += lblchecktable_Click;
                flowLayoutPanel1.Controls.Add(lbl2);
                chk_chkTable = true;
            }
        }

        private void lblchecktable_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Label)sender).Name == "lblchecktbleCheck")
                {
                    foreach (Control ctrl in flowLayoutPanel1.Controls)
                    {
                        if (ctrl.Name == "lblOtherfunc" | ctrl.Name == "lblNoteMenu" | ctrl.Name == "lblBreakTable" | ctrl.Name == "lblReportShifts" | ctrl.Name == "lblFastBuy" | ctrl.Name == "lblCheckTable")
                            ctrl.Visible = true;
                        else
                            ctrl.Visible = false;
                    }

                    foreach (Control ctrl in flowLayoutPanel3.Controls)
                    {
                        if (ctrl.Name == "lblQLBan" || ctrl.Name.Substring(0, 2) == "KV")
                            ctrl.Visible = true;
                        else
                            ctrl.Visible = false;
                    }
                }
                else if (((Label)sender).Name == "lblAvailableTable")
                {
                    foreach (Control ctrl in flowLayoutPanel3.Controls)
                    {
                        if (ctrl.Name.Substring(0, 1) == "B" & (ctrl.BackColor == Color.DodgerBlue || ctrl.BackColor == Color.SkyBlue))
                            ctrl.Visible = true;
                        else
                            ctrl.Visible = false;
                    }
                }
                else if (((Label)sender).Name == "lblNotAvailableTable")
                {
                    foreach (Control ctrl in flowLayoutPanel3.Controls)
                    {
                        if (ctrl.Name.Substring(0, 1) == "B" & (ctrl.BackColor == Color.DarkGreen || ctrl.BackColor == Color.DarkSeaGreen))
                            ctrl.Visible = true;
                        else
                            ctrl.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //bool chk_BreakTable = false; // Biến kiểm tra click lần đầu của tách bàn
        F_BreakTable bTble = null; // Form tách bàn

        private void lblBreakTable_Click(object sender, EventArgs e)
        {
            try
            {
                if (id_order != "")
                {
                    bool chk = false; // Biến kiểm tra in món xuống bếp
                    if (lstOrder.Groups[1].Items.Count > 0) // Xét có món đang gọi chưa in xuống bếp
                    {
                        DialogResult dialog = MessageBox.Show("Có món đang gọi chưa in xuống bếp, bạn muốn in xuống bếp và tách bàn không?", "Break Table", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                        if (dialog == DialogResult.Yes) // Nếu đồng ý
                            chk = true;
                        else
                            return;
                    }

                    if (chk || lstOrder.Groups[1].Items.Count == 0)
                    {
                        lblIn_Click(sender, e); // Lệnh in món xuống bếp

                        List<string> lstData = new List<string>();
                        string data = "";
                        foreach (ListViewItem items in lstOrder.Items)
                        {
                            if (items.Group.Name == "1")
                            {
                                data = "";
                                data += items.Text; // Tên món
                                data += "|" + items.SubItems[1].Text; //Số lượng
                                data += "|" + items.SubItems[2].Text; //Đơn giá gốc
                                data += "|" + items.SubItems[3].Text; //Mã món
                                data += "|" + items.SubItems[4].Text; //Xác định món trong menu hay ngoài menu
                                data += "|" + items.SubItems[5].Text; //Đơn giá khuyến mãi

                                lstData.Add(data);
                            }
                        }
                        bTble = new F_BreakTable(lstData, id_order, id_ban);
                        DialogResult dalog = bTble.ShowDialog();
                        if (dalog == DialogResult.Yes)
                        {
                            ClickOnTable(id_ban.ToString());
                            tinhtong();
                            Order_pro_DA.Update_Pro_BreakTable(id_order, Convert.ToDecimal(lblTongGiam.Text), Convert.ToDecimal(lblPhuThu.Text), Convert.ToDecimal(lblTongTien.Text));
                        }
                    }
                }
                else
                    MessageBox.Show("Chưa chọn bàn hoặc bàn chưa có order", "Err");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        bool chk_fastbuy = false; // Biến kiểm tra click nút bán nhanh lần đầu tiên (true: không phải lần đầu tiên / false: là lần đầu tiên)
        private void lblFastBuy_Click(object sender, EventArgs e)
        {
            fastbuy = true; // Gán giá trị cho phép bán nhanh
            // Khoá bàn
            foreach(Control ctrl in flowLayoutPanel3.Controls)
            {
                ctrl.Enabled = false;
            }
            // Reset trạng thái chọn bàn
            if (id_table != "" && flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor == Color.SkyBlue)
            {
                flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor = Color.DodgerBlue;
            }
            else if (id_table != "" && flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor == Color.DarkSeaGreen)
            {
                flowLayoutPanel3.Controls.Find(id_table, true)[0].BackColor = Color.DarkGreen;
            }
            id_ban = 0;
            lblBan.Text = ""; 
            if(lstOrder.Items.Count>0)
            {
                lstOrder.Items.Clear();
            }
            // Ẩn các nút chức năng
            foreach (Control ctrl in flowLayoutPanel1.Controls)
            {
                ctrl.Visible = false;
            }
            if (flowLayoutPanel1.Controls.Find("lblCancelFastBuy", true).Length > 0)
                flowLayoutPanel1.Controls.Find("lblCancelFastBuy", true)[0].Visible = true;
            else
            {
                /* Tạo nút hủy bán nhanh */
                Label lbl = new Label();
                lbl.Name = "lblCancelFastBuy";
                lbl.BackColor = Color.Teal;
                lbl.Text = "Hủy bán nhanh";
                lbl.Tag = "4";
                lbl.Margin = new System.Windows.Forms.Padding(0, 3, 0, 0);
                lbl.Size = new Size(114, 70);
                lbl.Font = new Font("Microsoft Sans Serif", 13);
                lbl.TextAlign = ContentAlignment.MiddleCenter;
                lbl.Click += lblCancelFastBuy;
                flowLayoutPanel1.Controls.Add(lbl);
            }
        }

        private void lblCancelFastBuy(object sender, EventArgs e)
        {
            //Nếu trên list có món ăn thì hỏi, nếu No thì không huỷ.
            if (lstOrder.Items.Count > 0 && MessageBox.Show("Bạn chưa tính tiền \n Bạn có muốn huỷ không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            //reset giá trị
            lstOrder.Items.Clear();
            lblTongGiam.Text = "0";
            lblPhuThu.Text = "0";
            lblTongTien.Text = "0";

            //Hiện lại các nút chức năng
            foreach (Control ctrl in flowLayoutPanel1.Controls)
            {
                if (ctrl.Name == "lblOtherfunc" | ctrl.Name == "lblNoteMenu" | ctrl.Name == "lblBreakTable" | ctrl.Name == "lblReportShifts" | ctrl.Name == "lblFastBuy" | ctrl.Name == "lblCheckTable")
                    ctrl.Visible = true;
                else
                    ctrl.Visible = false;
            }

            // Mở khoá bàn
            foreach (Control ctrl in flowLayoutPanel3.Controls)
            {
                ctrl.Enabled = true;
            }

            //reset biến cho phép bán nhanh
            fastbuy = false;
        }
    }
}
